需求就是求N!末尾零的个数,
因为没有确定N为多少,
但当N大于12时 int 型 已经存不下了,
所以不能求出来N的阶乘再看有多少个0,
所以最后决定根据 5的个数来确定末尾0的个数,
因为乘以一次5就会多出一个0,
有多少个5就有多少个0.
程序如下:
#include <iostream>
using namespace std;
int main()
{
int i,N,k;
double num;
char choice; //用来做循环的。。。
bool prime;
do
{
cout<<"*****************************"<<endl; //装饰界面的。。。
cout<<"Please input n:";
cin>>N;
k=0;
for(i=1;i<=N;i++) //查看有多少个5
{
num=i/5.0;
if(num-int(num)==0)
prime=true;
else
prime=false;
while(num>=1&&prime==true)
{
num/=5.0;
//这里需要再次判断num是否为整数
if(num-int(num)==0)
prime=true;
else
prime=false;
k+=1;
}
}
cout<<N<<"!(阶乘),末尾0的个数为:"<<k<<endl;
cout<<"*****************************"<<endl;
cout<<"是否继续输入N,继续则按任意键,退出则按N:";
cin>>choice;
cout<<"*****************************"<<endl;
}while(choice!='n'&&choice!='N');
cout<<endl;
return 0;
}
上面方法耗时太长了,要从1到N都判断一遍,显然有点浪费。
有更简单的方法:就是直接将除以5的答案累加起来,详情可见:http://blog.youkuaiyun.com/lttree/article/details/26234519
这道题还可以通过 POJ 1401来验证是否正确。
下面是耗时短的代码:
#include <iostream>
using namespace std;
int main()
{
int N,k,sum;
char choice; //用来做循环的。。。
do
{
cout<<"*****************************"<<endl; //装饰界面的。。。
cout<<"Please input n:";
cin>>N;
sum=0;
k=N;
while( k )
{
k/=5;
sum+=k;
}
cout<<N<<"!(阶乘),末尾0的个数为:"<<sum<<endl;
cout<<"*****************************"<<endl;
cout<<"是否继续输入N,继续则按任意键,退出则按N:";
cin>>choice;
cout<<"*****************************"<<endl;
}while(choice!='n'&&choice!='N');
cout<<endl;
return 0;
}
该博客介绍了如何用C++解决求N的阶乘末尾零的个数问题,通过分析5的个数来确定,而非直接计算阶乘,避免了整型溢出。提供了一种简单的解决方案,即累加N除以5的结果,并通过POJ 1401题目进行验证代码的正确性。
760





