gpt4 book ai didi

c++ - 需要 Codechef 练习题帮助 - 在阶乘中找到尾随零

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:26:04 24 4
gpt4 key购买 nike

我已经为此工作了 24 小时,试图对其进行优化。问题是如何在大约 8 秒内找到 10000000 和 1000 万个测试用例范围内的数字的阶乘中尾随零的数量。

代码如下:

#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;


}

请通过建议一种新方法或建议对此方法进行一些修改来帮助我。

最佳答案

使用下面的定理:

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

引用:PlanetMath

关于c++ - 需要 Codechef 练习题帮助 - 在阶乘中找到尾随零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2575373/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com