princeofsudan

ProjectEuler#26 Reciprocal cycles

Mar 20th, 2013
313
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.84 KB | None | 0 0
  1. #A unit fraction contains 1 in the numerator. The decimal representation of
  2. #the unit fractions with denominators 2 to 10 are given:
  3.  
  4. #    1/2    =   0.5
  5. #    1/3    =   0.(3)
  6. #    1/4    =   0.25
  7. #    1/5    =   0.2
  8. #    1/6    =   0.1(6)
  9. #    1/7    =   0.(142857)
  10. #    1/8    =   0.125
  11. #    1/9    =   0.(1)
  12. #    1/10   =   0.1
  13.  
  14. #Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle.
  15. #It can be seen that 1/7 has a 6-digit recurring cycle.
  16.  
  17. #Find the value of d < 1000 for which 1/d contains the longest recurring
  18. #cycle in its decimal fraction part.
  19.  
  20. #Problem: Floating point representation limitation.
  21. #Examble: 1/19.0 = 0.05263157894736842 while
  22. #1/19 = 0.052631578 947368421  ; 18 repeating digits
  23.  
  24. #Analysis:
  25. #Using long division to convert the fraction (rational number) into decimal form.
  26. #if any point the reminder is 0 its a terminating decimal.
  27. #if we arrive to a remainder as the one we began with, the decimal will start to repeat.
  28. #Source: http://en.wikipedia.org/wiki/Repeating_decimal
  29. #Section: Decimal expansion and recurrence sequence
  30.  
  31. max = 1000
  32. maxCount = 0
  33. maxDivisor = 0
  34. for divisor in range(2,max):
  35.     divdend = 10
  36.     quotient = []
  37.     reminder = []
  38.     while True:
  39.         if divdend < divisor:
  40.             quotient.append(0)
  41.             divdend *= 10
  42.         else:
  43.             quotient.append(divdend/divisor)
  44.             reminder.append((divdend%divisor)*10)
  45.             if reminder[-1] == 0:
  46.                 break
  47.             elif len(reminder) > 1 and reminder[-1] in\
  48.                  reminder[:len(reminder)-1]:
  49.                 break
  50.             divdend = reminder[-1]
  51.    
  52.     if reminder[-1] != 0:
  53.         while quotient[0] == 0:
  54.             quotient.remove(0)
  55.         if len(quotient)-1 >= maxCount:
  56.             maxCount = len(quotient)-1
  57.             maxDivisor = divisor
  58.        
  59. print maxDivisor, maxCount
Advertisement
Add Comment
Please, Sign In to add comment