Euler Problem 26

A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given:

1/2  =  0.5
1/3  =  0.(3)
1/4  =  0.25
1/5  =  0.2
1/6  =  0.1(6)
1/7  =  0.(142857)
1/8  =  0.125
1/9  =  0.(1)
1/10    =   0.1

Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be seen that 1/7 has a 6-digit recurring cycle.

Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part.

The trick here is to identify a cycle. The easiest way I see to do this is to memorize the remainders. If we have a remainder that we occurred previously there is a cycle.

Let's consider 1/3. The initial remainder is 10. For ten divided by three the new remainder is again ten (or one times ten). So we have a one-cycle of 3.

In [1]:
def get_cycle_count(nominator, denominator):
    from itertools import count
    assert(nominator == 1)
    remainders = {}
    remainder = nominator
    results = []
    for i in count():
        result = remainder // denominator
        remainder = remainder % denominator
        results.append(result)
        if remainder in remainders:
            return i - remainders[remainder]
        else:
            remainders[remainder] = i
        if remainder == 0:
            return 0
        remainder *= 10

assert(get_cycle_count(1, 7) == 6)
assert(get_cycle_count(1, 10) == 0)
assert(get_cycle_count(1, 6) == 1)

This is a simple divison algorithm. The only special thing is the remainder and that we remember when it occurs the first time. If a remainder occurrs for the second time we substract the position and thus have the lenght of the cycle. With this solution we should be efficient enough to brute force.

In [2]:
s = max([(get_cycle_count(1, i), i)for i in range(1, 1000)])
s = s[1]
assert(s == 983)
print(s)
983