Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Euler 160 : Find the non trivial 5 digits of the factorial

Tags:

c

algorithm

math

Given a number find the 5 digits before the trailing 0. 9! = 362880 so f(9)=36288 10! = 3628800 so f(10)=36288 20! = 2432902008176640000 so f(20)=17664 Find f(1,000,000,000,000)

For this I have computed the f(10^6) and then f(10^12) = (f(10^6))^(10^6) for computing the f(n) ... I am computing the factorial by removing any 5 and corresponding 2 so that all the trailing zeros are removed.
But I am getting a wrong answer.
Is there a problem in approach or some silly mistake ?

Code for reference

long long po(long long n, long long m, long long mod) {
    if (m == 0) return 1;
    if (m == 1) return n % mod;
    long long r = po(n, m / 2, mod) % mod;
    if (m % 2 == 0) return (r * r) % mod;
    return (((r * r) % mod) * n) % mod;
}

void foo() {
    unsigned long long i, res = 1, m = 1000000 , c = 0, j, res1 = 1, mod;
    mod = ceil(pow(10, 9));
    cout << mod << endl;
    long long a = 0, a2 = 0, a5 = 0;
    for (i = 1 ; i <= m; i++) {
        j = i;
        while (j % 10 == 0)
            j /= 10;
        while (j % 2 == 0) {
            j /= 2;
            a2++;
        }
        while (j % 5 == 0) {
            j /= 5;
            a5++;
        }
        res = (res * j ) % mod;
    }

    a = a2 - a5;

    for (i = 1; i <= a; i++)
        res = (res * 2) % mod;
    for (i = 1; i <= 1000000; i++) {
        res1 = (res1 * res) % mod;
    }
    cout << res1 << endl;
}
like image 484
titan Avatar asked Feb 17 '12 18:02

titan


1 Answers

Your equality f(10^12) = (f(10^6))^(10^6) is wrong. f() is based on factorials, not powers.

like image 131
Ned Batchelder Avatar answered Sep 17 '22 01:09

Ned Batchelder