Euler 160:找到阶乘的非平凡5位数

tit*_*tan 5 c algorithm math

给定一个数字,在尾随0. 9之前找到5位数!= 362880所以f(9)= 36288 10!= 3628800所以f(10)= 36288 20!= 2432902008176640000所以f(20)= 17664查找f(1,000,000,000,000)

为此,我计算了f(10^6)然后f(10^12) = (f(10^6))^(10^6) 计算f(n)...我通过删除任何5和相应的2来计算阶乘,以便删除所有尾随零.
但我得到了错误的答案.
方法有问题还是有些愚蠢的错误?

代码供参考

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;
}
Run Code Online (Sandbox Code Playgroud)

Ned*_*der 6

你的平等f(10^12) = (f(10^6))^(10^6)是错的.f()基于阶乘,而不是幂.

  • @titan:但是数字中的尾随零意味着你不能像那样对待整个问题模块1000000.例如,你的第一个百万中的123000将为5比1123000提供不同的数字,所以它们不相等. (6认同)