def sum_mod(m): mod = 9 % m while True: yield mod mod = ((mod * 10) + 9) % m def exact_div(m): if not m: return 0 while not (m % 2): m //= 2 while not (m % 5): m //= 5 if 1 == m: return 0 for i, value in enumerate(sum_mod(m)): if not value: return i + 1 def max_cycle(limit): cycles = [exact_div(x) for x in range(limit + 1)] return cycles.index(max(cycles)) print(max_cycle(1000))