aks_primality_test.sf 916 B

12345678910111213141516171819202122232425262728293031323334
  1. #!/usr/bin/ruby
  2. # A simple (non-practical) implementation of the AKS primality test.
  3. func aks_primality_test(n) {
  4. # Algorithm 4.1.5, described in the book "Prime Numbers - A computational perspective".
  5. # Make sure n is not a perfect power
  6. return false if n.is_power
  7. # Find the least integer r with znorder(n, r) > (log_2(n))^2
  8. var r = (n.ilog2**2 .. Inf -> lazy.grep{.is_prime}.first_by {|m|
  9. znorder(n, m) > n.log2**2
  10. })
  11. # If n has a proper factor in [2, sqrt(phi(n)) * log_2(n)], then n is composite
  12. var max_a = floor(sqrt(phi(r))*n.log2)
  13. n.trial_factor(max_a).len == 1 || return false
  14. # Binomial congruences
  15. var x = Poly(1).mod(n)
  16. var m = (Poly(r) - 1)
  17. for k in (1..max_a) {
  18. var a = Mod(k, n)
  19. (x + a).powmod(n, m) == (x.powmod(n, m) + a) || return false
  20. }
  21. return true
  22. }
  23. say 10.by(aks_primality_test) # first 10 primes