legendre_factorial.sf 469 B

123456789101112131415161718192021222324252627
  1. #!/usr/bin/ruby
  2. # An efficient algorithm for computing N-factorial, using power of primes.
  3. # See also:
  4. # https://en.wikipedia.org/wiki/Legendre%27s_formula
  5. func legendre_power(p,n) {
  6. var s = 0
  7. while (n >= p) {
  8. s += n.idiv!(p)
  9. }
  10. return s
  11. }
  12. func legendre_factorial(n) {
  13. var f = 1
  14. for p in (primes(n)) {
  15. f *= p**legendre_power(p,n)
  16. }
  17. return f
  18. }
  19. for n in (0..20) {
  20. say "#{'%2d' % n}! = #{legendre_factorial(n)}"
  21. }