fibonacci-fermat_primality_test.sf 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. #!/usr/bin/ruby
  2. # Daniel "Trizen" Șuteu
  3. # License: GPLv3
  4. # Date: 11 August 2018
  5. # https://github.com/trizen
  6. # A simple primality test with respect to Fibonacci polynomial x^2-x-1, and a base-2 Fermat test.
  7. # Smallest counter-examples are:
  8. # 219781, 252601, 399001, 512461, 722261, 741751, 852841, 1024651, 1193221, 1533601, 1690501, 1735841, 1857241, 1909001, 2100901
  9. # See also:
  10. # https://oeis.org/A212424
  11. # https://en.wikipedia.org/wiki/Fermat_primality_test
  12. # https://en.wikipedia.org/wiki/Frobenius_pseudoprime
  13. func fibonacci_fermat_primality_test(n) {
  14. return false if (n <= 1)
  15. return true if (n == 2)
  16. return true if (n == 5)
  17. powmod(2, n-1, n) == 1 || return false
  18. var k = kronecker(5, n)
  19. fibmod(n - k, n) == 0 || return false
  20. fibmod(n + k, n) == 1 || return false
  21. return true
  22. }
  23. # Test some Carmichael numbers
  24. var carmichael = [252601, 278545, 294409, 314821, 334153, 340561, 399001, 410041, 449065, 488881, 512461]
  25. say carmichael.grep {|n| fibonacci_fermat_primality_test(n) } #=> [252601, 399001, 512461]
  26. # Filter the primes in a given range
  27. say {|n| fibonacci_fermat_primality_test(n) }.grep(15912519589..15912519859) #=> [15912519629, 15912519643, 15912519661, 15912519769, 15912519829, 15912519839, 15912519851, 15912519853]