Skip to content

Instantly share code, notes, and snippets.

@Hermann-SW
Created November 19, 2022 12:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Hermann-SW/6379e236f7c48f2eefe26d83e62b0cea to your computer and use it in GitHub Desktop.
Save Hermann-SW/6379e236f7c48f2eefe26d83e62b0cea to your computer and use it in GitHub Desktop.
fac(n) computes factorial, facmod(n, m) is faster in reducing all recursive results "mod m"
define fac(n) {
if (n==0) return 1;
return n*fac(n-1)
}
define facmod(n, m) {
if (n==0) return 1;
return n*fac(n-1)%m
}
@Hermann-SW
Copy link
Author

Hermann-SW commented Nov 19, 2022

Wilson's theorem:
(n-1)! ≡ -1 (mod n) ⇔ n is prime
https://en.wikipedia.org/wiki/Wilson%27s_theorem

pi@pi400-64:~ $ time (echo "facmod(9972, 9973)" | bc -q fac.bc )
9972

real	0m6.119s
user	0m5.550s
sys	0m0.050s
pi@pi400-64:~ $
pi@pi400-64:~ $ bc -q fac.bc
fac(0)
1
fac(10)
3628800

Only for n starting at 30,000 "fac(n)%m" becomes slower than "facmod(n, m)":

pi@pi400-64:~ $ time (echo "fac(39988)%39989" | bc -q fac.bc )
39988

real	0m55.654s
user	0m54.578s
sys	0m0.959s
pi@pi400-64:~ $ time (echo "facmod(39988, 39989)" | bc -q fac.bc )
39988

real	0m52.071s
user	0m51.061s
sys	0m0.897s
pi@pi400-64:~ $ 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment