Friday, August 29, 2014

Project Euler Problem 26 Solution

Reciprocal cycles

Problem 26

A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given:
1/20.5
1/30.(3)
1/40.25
1/50.2
1/60.1(6)
1/70.(142857)
1/80.125
1/90.(1)
1/100.1
Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be seen that 1/7 has a 6-digit recurring cycle.
Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part.





Math Concept:

The fraction of the Prime number P except 2, 5 always produce repeated cycles in fractional part, which are most likely of the factor of P-1 or at most P-1.

According to Fermat's theorem, length of the repeated part is given as follows:
10^n mod P = 1

now, this n can be either P-1 or factor of P-1

All we need to do is start from 1000 downwards looking for prime numbers, which satisfies P-1 length.


NOTE: ELEGANT EXAMPLE OF QUICK SOLUTION IF YOU KNOW MATH :)

def is_prime(n):
  i = 2
  while i*i <= n:
    if n%i == 0:
      return False
    i = i + 1

  return True

def generate_prime_below(n):
  l1 = []

  for i in range(n,1,-1):
    if is_prime(i):
      l1.append(i)

  return l1

for p in generate_prime_below(1000):
  c = 1
  while pow(10,c,p) != 1:
    c = c + 1

  if p-c == 1:
    break

print p 


ANSWER = 983 




Thanks

2 comments:

  1. Would (exchanging c with e for my own purposes)

    for p in generate_prime_below(1000):
    e = 1
    # Start at e=1 and continue to increment e
    while pow(10, e, p) != 1:
    e += 1
    # Stop when 10^e(mod p) ≡ 1 and e is (p-1) or a factor of (p-1). See Fermat's Little Theorem.
    if pow(10, e, p) == 1 and e == p - 1:
    break

    be more clear? I'm not sure why you wrote p - c == 1.

    ReplyDelete
  2. Actually, it should be a^(p-1)-1=0 (mod p). So, you shouldn't be looking for a factor of p-1.

    ReplyDelete