Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- Let be n an integer prime with 10 e.g. 7.
- 1/7 = 0.142857 142857 142857 ....
- We see that the decimal part has a cycle: 142857. The length of this cycle is 6. In the same way:
- 1/11 = 0.09 09 09 .... Cycle length is 2.
- Task
- Given an integer n (n > 1) the function cycle(n) returns the length of the cycle if there is one otherwise (n and 10 not coprimes) return -1.
- Examples
- cycle(5) = -1
- cycle(13) = 6 -> 0.076923 076923 0769
- cycle(21) = 6 -> 0.047619 047619 0476
- cycle(27) = 3 -> 0.037 037 037 037 0370
- cycle(33) = 2 -> 0.03 03 03 03 03 03 03 03
- cycle(37) = 3 -> 0.027 027 027 027 027 0
- cycle(94) = -1
- '''
- def cycle(n):
- if n % 10 == 0:
- print("There is a problem while using function " + cycle.__name__)
- return -1
- klasma = str(1 / n)
- # I will take the quantity after "0.", so I will start from index 2
- quantity = klasma[2:]
- print("n = " + str(n) + " ----> quantity = " + str(quantity))
- N = len(quantity)
- # First, I have to check if the 1st digit appears again
- # If this case doesn't happen, then we know that there is no posiibility of a cycle and we return -1
- first = quantity[0]
- appears = False
- index = -1000
- for i in range(1, N):
- if quantity[i] == first:
- appears = True
- index = i
- break
- if appears == False:
- return -1
- # We continue here since we have found that the first digit appears again
- # We also know that Python "holds" max = 17 decimal places
- flag = True
- for i in range(0, N - index - 1): # I put "-1" for precision errors
- for j in range(0, index):
- if quantity[i] != quantity[i+index]:
- # print(quantity[i], quantity[i+index])
- flag = False
- if flag == False:
- return -1
- return index
- # MAIN FUNCTION
- for n in range(2, 100):
- print(cycle(n))
- print()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement