首页 > 试题广场 >

对任意输入的正整数N,编写C程序求N!的尾部连续0的个数,并

[问答题]
对任意输入的正整数N,编写C程序求N!的尾部连续0的个数,并指出计算复杂度。如:18!=6402373705728000,尾部连续0的个数是3。
(不用考虑数值超出计算机整数界限的问题)

#include<iostream>

using namespace std;
void Fun(int n)
{
    int count  = 0;
    while (n)
    {
        n /= 5;
        count += n;
    }

    cout<<count<<endl;
}
int main()
{
    int n = 0;
    cin>>n;
    Fun(n);

    return 0;
}

发表于 2015-06-28 22:34:51 回复(0)
int ZerosForN_3(int n)
{
    int result=0;
    n/=5;  
    while(n >0)
        {
        result += n; 
        n/=5;        
     }
    return result;
}

等比数列的项数为log5(N),即为循环的次数,故复杂度为log5(N) 

编辑于 2015-06-28 11:35:44 回复(0)
#include<iostream>
#include<string>
using namespace std;
int main(){
    int n;
    cin>>n;
    int a=1;
    while (n>0)
    {
        a=n*a;
        n--;
    }
    int cnt=0;
    if (a%10==0)
    {
        cnt++;
        a=a/10;
    }
    cout<<cnt;
    return 0;
}

编辑于 2015-06-28 12:33:33 回复(0)