Possible Duplicate:
Fast way to calculate n! mod m where m is prime?
Let:
int k = 99999989;
k
is a prime number.
Given some (32-bit) int x
, we want to calculate x factorial mod k. (x! % k)
One way to do this is as follows:
int factmk(int x)
{
long long t = 1;
for (long long i = 2; i <= x; i++)
{
t *= i;
t %= k;
}
return (int)t;
};
This requires O(x) time, and O(1) space.
Is there an asymptotically faster way to implement factmk
in straight C in less than or equal to O(logx) space? If yes, what is it? If no, sketch proof.