-
Notifications
You must be signed in to change notification settings - Fork 0
/
problem026.py
66 lines (50 loc) · 1.9 KB
/
problem026.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#!/usr/bin/env python
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Project Euler
# Problem 26
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
###########################################
### IMPORTS ###
###########################################
###########################################
### GLOBALS ###
###########################################
###########################################
### FUNCTION DEFS ###
###########################################
#=============================================================================#
# Finds the length of reciprocal cycle for a number n
# We keep track of remainders--once we hit the same remainder, we have
# finished our cycle.
def find_cycle_len(n):
# initialize tracker
tracker = [-1] * n
# initialize remainder (starts at 1)
r = 1
# by pidgeonhole, we need at most n iterations to find a cycle
for i in range(n):
# if remainder is 0, cycle is 0 since decimal terminates
if r == 0:
return 0
# check if remainder has already been reached
if tracker[r] >= 0:
return i - tracker[r]
# otherwise, mark the remainder as reached
tracker[r] = i
# calculate new remainder
while (r < n):
r *= 10
r = r % n
return -1
###########################################
### MAIN FUNCTION ###
###########################################
max_cycle_len = 0
max_cycle_denom = 1
for i in range(2, 1000):
i_cycle_len = find_cycle_len(i)
print('%d: %d' % (i, i_cycle_len))
if i_cycle_len > max_cycle_len:
max_cycle_len = i_cycle_len
max_cycle_denom = i
print('Longest cycle is 1/%d with length %d' % (max_cycle_denom, max_cycle_len))