If you're always guaranteed a solution (at least for even n
and multiples of 5
, there is no solution. I haven't given it much thought for others, but I think the rest should always have a solution):
(a + b) % c = ((a % c) + (b % c)) % c
(a * b) % c = ((a % c) * (b % c)) % c
Where %
is the modulo operator: a % b = the remainder of the division of a by b
. This means that we can take modulos between additions and multiplications, which will help solve this problem.
Using this, you can use the following algorithm, which is linear in the number of digits of the result and uses O(1)
memory:
number_of_ones = 1
remainder = 1 % n
while remainder != 0:
++number_of_ones
# here we add another 1 to the result,
# but we only store the result's value mod n.
# When this is 0, that is our solution.
remainder = (remainder * 10 + 1) % n
print 1 number_of_ones times
Followup question: what if you can use 0
and 1
?