def get_cycle(d): remainders = [] x = 1 while x > 0: if x < d: x *= 10 continue z = x / d x = (x % d) * 10 if x in remainders: # cycle detected pos = 0 for i in range(len(remainders)): if remainders[i] == x: return len(remainders) - i break remainders += [x] return 0 # no cycle max_remainder = 0 result = 0 for i in range(1, 1000): r = get_cycle(i) if r > max_remainder: max_remainder = r result = i print result