Codechef实践问题需要帮助 - 在阶乘中找到尾随零 [英] Codechef practice question help needed - find trailing zeros in a factorial

查看:111
本文介绍了Codechef实践问题需要帮助 - 在阶乘中找到尾随零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经工作了24小时,尝试优化它。问题是如何在大约8秒内找到10000000和1000万个测试用例范围内的数字的阶乘零数。

I have been working on this for 24 hours now, trying to optimize it. The question is how to find the number of trailing zeroes in factorial of a number in range of 10000000 and 10 million test cases in about 8 secs.

代码如下:

#include<iostream>

using namespace std;

int count5(int a){
    int b=0;
    for(int i=a;i>0;i=i/5){
        if(i%15625==0){
            b=b+6;
            i=i/15625;
        }
        if(i%3125==0){
            b=b+5;
            i=i/3125;
        }
        if(i%625==0){
            b=b+4;
            i=i/625;
        }
        if(i%125==0){
            b=b+3;
            i=i/125;
        }
        if(i%25==0){
            b=b+2;
            i=i/25;
        }
        if(i%5==0){
            b++;
        }
        else
            break;

    }
    return b;
}
int main(){
    int l;
    int n=0;
    cin>>l; //no of test cases taken as input
    int *T = new int[l];

    for(int i=0;i<l;i++)
        cin>>T[i]; //nos taken as input for the same no of test cases


    for(int i=0;i<l;i++){
        n=0;
        for(int j=5;j<=T[i];j=j+5){
            n+=count5(j); //no of trailing zeroes calculted 
        }
        cout<<n<<endl; //no for each trialing zero printed
    }

    delete []T;


}   

请帮助我,或建议对此修改。

Please help me by suggesting a new approach, or suggesting some modifications to this one.

推荐答案

使用以下定理:


如果p是素数,那么p的最高
次幂。 (n
阶乘)是[n / p] + [n / p ^ 2] +
[n / p ^ 3] + ... + [n / p ^ k]
p <= n的最大幂,[x]是x的整数部分。

If p is a prime, then the highest power of p which divides n! (n factorial) is [n/p] + [n/p^2] + [n/p^3] + ... + [n/p^k], where k is the largest power of p <= n, and [x] is the integral part of x.

http://planetmath.org/encyclopedia/PrimePowerDividingAFactorial.html

这篇关于Codechef实践问题需要帮助 - 在阶乘中找到尾随零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆