calgorithmmathmodulus

Calculating n! mod m when m is not prime


I have read a lot of good algos to calculate n! mod m but they were usually valid when m was prime . I wanted to know whether some good algo exists when m is not prime .I would be helpful if someone could write the basic function of the algo too.I have been using

long long factMOD(long long n,long long mod)
{
    long long res = 1; 
    while (n > 0)
    {
        for (long long i=2, m=n%mod; i<=m; i++)
        res = (res * i) % mod;
        if ((n/=mod)%2 > 0) 
        res = mod - res;
    }
    return res;
}

but getting wrong answer when I try to print factMOD(4,3) even. source of this algo is :
http://comeoncodeon.wordpress.com/category/algorithm/


Solution

  • This is what I've come up with:

    #include <stdio.h>
    #include <stdlib.h>
    
    unsigned long long nfactmod(unsigned long long n, unsigned long long m)
    {
        unsigned long long i, f;
        for (i = 1, f = 1; i <= n; i++) {
            f *= i;
            if (f > m) {
                f %= m;
            }
        }
        return f;
    }
    
    int main(int argc, char *argv[])
    {
        unsigned long long n = strtoull(argv[1], NULL, 10);
        unsigned long long m = strtoull(argv[2], NULL, 10);
    
        printf("%llu\n", nfactmod(n, m));
    
        return 0;
    }
    

    and this:

    h2co3-macbook:~ h2co3$ ./mod 1000000 1001001779
    744950559
    h2co3-macbook:~ h2co3$
    

    runs in a fraction of a second.