Calculates the cycle length of a cyclic decimal
I want to make a program in python (3.6.5) to tell, for example, 1/7. The output of this example should be similar to: “Length: 6, Repeat numbers: 142857”. So far I got this :
n = int(input("numerator: "))
d = int(input("denominator: "))
def t(n, d):
x = n * 9
z = x
k = 1
while z % d:
z = z * 10 + x
k += 1
print ("length:", k)
print ("repeated numbers:", t)
return k, z / d
t(n, d)
Solution
Execute print("repeated numbers:"
, t) to print a representation of the t
function itself, not its output.
This is a fixed version of your code. I used Python 3.6+ f-string to convert repeated numbers to strings, adding zeros in front to make them the correct length.
def find_period(n, d):
z = x = n * 9
k = 1
while z % d:
z = z * 10 + x
k += 1
digits = f"{z // d:0{k}}"
return k, digits
# Test
num, den = 1, 7
period, digits = find_period(num, den)
print('num:', num, 'den:', den, 'period:', period, 'digits:', digits)
num, den = 1, 17
period, digits = find_period(num, den)
print('num:', num, 'den:', den, 'period:', period, 'digits:', digits)
Output
num: 1 den: 7 period: 6 digits: 142857
num: 1 den: 17 period: 16 digits: 0588235294117647
This line may be a bit mysterious:
f"{z // d:0{k}}"
It says: Find the largest integer less than or equal to z
divided by d
, convert it to a string, and fill it with zeros on the left (if necessary) to give it a length of k.
As Goyo points out in his review, the algorithm is not perfect. If the decimal contains any non-repeating parts, i.e. if the denominator has any factor of 2 or 5, it gets stuck in a loop. See if you can come up with a way to deal with this.