aks_primality_test_n-1_variant.sf 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #!/usr/bin/ruby
  2. # A simple (non-practical) implementation of the n-1 variant of the AKS primality test.
  3. func aks_primality_test(n) {
  4. # Theorem 4.5.7, described in the book "Prime Numbers - A computational perspective".
  5. # Let n,r,b be integers with n > 1 and r | (n-1), r > (log_2(n))^2,
  6. # b^(n-1) == 1 (mod n) and gcd(b^((n-1)/q) - 1, n) = 1 for each prime q|r.
  7. # If (x-1)^n == x^n - 1 (mod x^r - b, n), then n is a prime or a prime power.
  8. # Make sure n is not a perfect power
  9. return false if n.is_power
  10. # n-1 must be greater than (log_2(n))^2
  11. n-1 > n.log2**2 || return n.is_prime
  12. return false if n.is_even
  13. # Find the smallest divisor d of n-1 that is greater than (log_2(n))^2
  14. var r = (1..Inf -> lazy.map {|k|
  15. divisors(n-1, (n.ilog2**2) << k).first {|d|
  16. d > n.log2**2
  17. }
  18. }.first_by { _ != nil })
  19. var f = r.factor_exp.map { .head }
  20. # Find b such that b^(n-1) == 1 (mod n) and gcd(b^((n-1)/q) - 1, n) = 1 for each prime q|r.
  21. var b = (1..Inf -> lazy.map { irand(2, n-2) }.first_by { |b|
  22. powmod(b, n-1, n) == 1 || return false
  23. f.all {|q|
  24. var g = gcd(powmod(b, idiv(n-1, q), n) - 1, n)
  25. g.is_between(2, n-1) && return false
  26. g == 1
  27. }
  28. })
  29. # Binomial congruence
  30. var x = Poly(1).mod(n)
  31. var m = (Poly(r) - b)
  32. (x - 1).powmod(n, m) == (x.powmod(n, m) - 1)
  33. }
  34. say 15.by(aks_primality_test) # first 15 primes