Does anyone know a method for computing the quantity of
n! mod M
such that overflow is not an issue? I cannot think of anything where such a large value of n would not cause a problem.
Does anyone know a method for computing the quantity of
n! mod M
such that overflow is not an issue? I cannot think of anything where such a large value of n would not cause a problem.
Assuming that n * (n-1)
does not overflow, you can just take the product mod M
after every multiplication.
Update: As Dukeling
very patiently explained to me, the assumption above is not a sufficient condition to ensure that method of applying mod M
after each multiplication will guarantee no overflow.
The sufficient condition is that (M-1)*(n mod M)
does not overflow, because that is the largest possible product that could result before the mod
is taken.
If you use a Big Integer library, it will never overflow. However, depending on the algorithm and the number of digits you want, it might take years to execute.