026 Reciprocal cycles.jl 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #!/usr/bin/julia
  2. # Daniel "Trizen" Șuteu
  3. # Edit: 25 July 2021
  4. # https://github.com/trizen
  5. # Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part.
  6. # https://projecteuler.net/problem=26
  7. # Runtime: 1.014s
  8. using Primes
  9. function divisors(n)
  10. d = Int64[1]
  11. for (p,e) in factor(n)
  12. t = Int64[]
  13. r = 1
  14. for i in 1:e
  15. r *= p
  16. for u in d
  17. push!(t, u*r)
  18. end
  19. end
  20. append!(d, t)
  21. end
  22. return sort(d)
  23. end
  24. function znorder(a, n)
  25. if isprime(n)
  26. for d in divisors(n-1)
  27. if (powermod(a, d, n) == 1)
  28. return d
  29. end
  30. end
  31. end
  32. f = factor(n)
  33. if (length(f) == 1) # is prime power
  34. p = first(first(f))
  35. z = znorder(a, p)
  36. while (powermod(a, z, n) != 1)
  37. z *= p
  38. end
  39. return z
  40. end
  41. pp_orders = Int64[]
  42. for (p,e) in f
  43. push!(pp_orders, znorder(a, p^e))
  44. end
  45. return lcm(pp_orders)
  46. end
  47. function p_26()
  48. d,m = 1,0
  49. for n in 2:1000
  50. gcd(10, n) == 1 || continue
  51. r = znorder(10, n)
  52. if (r > m)
  53. m,d = r,n
  54. end
  55. end
  56. return d
  57. end
  58. println(p_26())