pisano_periods.sf 573 B

123456789101112131415161718192021222324252627
  1. #!/usr/bin/ruby
  2. # Compute the Pisano periods (or Pisano numbers): period of Fibonacci numbers mod n.
  3. # See also:
  4. # https://oeis.org/A001175
  5. # https://en.wikipedia.org/wiki/Pisano_period
  6. func pisano_period_pp(p,k) is cached {
  7. assert(k.is_pos, "k = #{k} must be positive")
  8. assert(p.is_prime, "p = #{p} must be prime")
  9. var (a, b, n) = (0, 1, p**k)
  10. 1..Inf -> first_by {
  11. (a, b) = (b, (a+b) % n)
  12. (a == 0) && (b == 1)
  13. }
  14. }
  15. func pisano_period(n) {
  16. n.factor_map {|p,k| pisano_period_pp(p, k) }.lcm
  17. }
  18. say pisano_period.map(1..20)