fibonacci_k-th_order_period.sf 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #!/usr/bin/ruby
  2. # Daniel "Trizen" Șuteu
  3. # Date: 23 January 2019
  4. # https://github.com/trizen
  5. # Find the Pisano period of k-th order Fibonacci numbers modulo m (also called k-step Fibonacci numbers).
  6. # OEIS sequences:
  7. # https://oeis.org/A001175 -- Pisano periods (or Pisano numbers): period of Fibonacci numbers mod n.
  8. # https://oeis.org/A046738 -- Period of Fibonacci 3-step sequence A000073 mod n.
  9. # https://oeis.org/A106303 -- Period of the Fibonacci 5-step sequence A001591 mod n.
  10. # See also:
  11. # https://en.wikipedia.org/wiki/Pisano_period
  12. # https://en.wikipedia.org/wiki/Generalizations_of_Fibonacci_numbers#Fibonacci_numbers_of_higher_order
  13. func fibonacci_kth_order_period(m, k) {
  14. return 0 if (m == 0)
  15. return 1 if (m == 1)
  16. if (!m.is_prime) {
  17. return m.factor_map {|p,e|
  18. __FUNC__(p, k) * p**(e-1) # Wall's conjecture
  19. }.lcm
  20. }
  21. var nth = k+1
  22. var count = 1
  23. var arr = k.of { fibonacci(_, k)%m }
  24. var target = arr.clone
  25. do {
  26. arr << fibonacci(nth, k)%m
  27. arr.shift
  28. ++count
  29. ++nth
  30. } while (arr != target)
  31. return count
  32. }
  33. for k in (2..4) {
  34. var n = 10
  35. say ("Period of the Fibonacci #{k}-step numbers mod m=1..#{n}: ", n.of { fibonacci_kth_order_period(_+1, k) })
  36. }
  37. __END__
  38. Period of the Fibonacci 2-step numbers mod m=1..10: [1, 3, 8, 6, 20, 24, 16, 12, 24, 60]
  39. Period of the Fibonacci 3-step numbers mod m=1..10: [1, 4, 13, 8, 31, 52, 48, 16, 39, 124]
  40. Period of the Fibonacci 4-step numbers mod m=1..10: [1, 5, 26, 10, 312, 130, 342, 20, 78, 1560]
  41. Period of the Fibonacci 5-step numbers mod m=1..10: [1, 6, 104, 12, 781, 312, 2801, 24, 312, 4686]
  42. Period of the Fibonacci 6-step numbers mod m=1..10: [1, 7, 728, 14, 208, 728, 342, 28, 2184, 1456]