jacobi_symbol.sf 687 B

1234567891011121314151617181920212223242526272829303132
  1. #!/usr/bin/ruby
  2. # Simple implementation of the Jacobi symbol (a|n).
  3. # See also:
  4. # https://rosettacode.org/wiki/Jacobi_symbol
  5. # https://en.wikipedia.org/wiki/Jacobi_symbol
  6. # https://en.wikipedia.org/wiki/Kronecker_symbol
  7. func jacobi(a, n) {
  8. assert(n > 0, "#{n} must be positive")
  9. assert(n.is_odd, "#{n} must be odd")
  10. var t = 1
  11. while (a %= n) {
  12. if (a.is_even) {
  13. var v = a.valuation(2)
  14. t *= (-1)**v if (n%8 ~~ [3,5])
  15. a >>= v
  16. }
  17. (a,n) = (n,a)
  18. t = -t if ([a%4, n%4] == [3,3])
  19. }
  20. n==1 ? t : 0
  21. }
  22. for a in (0..10), n in (0..10) {
  23. assert_eq(jacobi(a, 2*n + 1), kronecker(a, 2*n + 1))
  24. }