Advertisement
makispaiktis

Codewars - 1/n Cycle

Mar 15th, 2021 (edited)
1,109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.89 KB | None | 0 0
  1. '''
  2. Let be n an integer prime with 10 e.g. 7.
  3. 1/7 = 0.142857 142857 142857 ....
  4. We see that the decimal part has a cycle: 142857. The length of this cycle is 6. In the same way:
  5. 1/11 = 0.09 09 09 .... Cycle length is 2.
  6. Task
  7. 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.
  8. Examples
  9. cycle(5) = -1
  10. cycle(13) = 6 -> 0.076923 076923 0769
  11. cycle(21) = 6 -> 0.047619 047619 0476
  12. cycle(27) = 3 -> 0.037 037 037 037 0370
  13. cycle(33) = 2 -> 0.03 03 03 03 03 03 03 03
  14. cycle(37) = 3 -> 0.027 027 027 027 027 0
  15. cycle(94) = -1
  16. '''
  17.  
  18. def cycle(n):
  19.     if n % 10 == 0:
  20.         print("There is a problem while using function " + cycle.__name__)
  21.         return -1
  22.     klasma = str(1 / n)
  23.     # I will take the quantity after "0.", so I will start from index 2
  24.     quantity = klasma[2:]
  25.     print("n = " + str(n) + " ----> quantity = " + str(quantity))
  26.     N = len(quantity)
  27.     # First, I have to check if the 1st digit appears again
  28.     # If this case doesn't happen, then we know that there is no posiibility of a cycle and we return  -1
  29.     first = quantity[0]
  30.     appears = False
  31.     index = -1000
  32.     for i in range(1, N):
  33.         if quantity[i] == first:
  34.             appears = True
  35.             index = i
  36.             break
  37.     if appears == False:
  38.         return -1
  39.     # We continue here since we have found that the first digit appears again
  40.     # We also know that Python "holds" max = 17 decimal places
  41.     flag = True
  42.     for i in range(0, N - index - 1):       # I put "-1" for precision errors
  43.         for j in range(0, index):
  44.             if quantity[i] != quantity[i+index]:
  45.                 # print(quantity[i], quantity[i+index])
  46.                 flag = False
  47.     if flag == False:
  48.         return -1
  49.     return index
  50.  
  51.  
  52. # MAIN FUNCTION
  53. for n in range(2, 100):
  54.     print(cycle(n))
  55.     print()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement