牛客小白月赛5----D 阶乘(factorial)

链接:https://www.nowcoder.com/acm/contest/135/D
来源:牛客网
 

题目描述

输入描述:

输入数据共一行,一个正整数n,意义如“问题描述”。

输出描述:

输出一行描述答案:

一个正整数k,表示S的末尾有k个0

示例1

输入

10

输出

7

说明

我们知道两数相乘末尾产生零的情况只有2*5,我们的目的就是要计算因子2,5出现的次数,找到而这种最小的次数。

由于2出现的次数一定大于5出现的次数,那我我们只需要找到5出现的次数就好了。那么我们可以遍历5 10 15......

统计5出现的次数。

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n,count=0,j;
    scanf("%d",&n);
    for(int i=5;i<=n;i+=5)
    {
        j=i;
        while(j%5==0)
        {
            count++;
            j/=5;
        }
    }
    printf("%d\n",count);
    return 0;
}

解题思路:上面是n的阶乘出现5的次数,那么如果我们从1开始遍历,我们每循环一次就能找到 i! 中5出现的次数,每次循环都把count保存。最后就能得到结果。

AC代码:

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n,j;
    long long sum=0,count=0;
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
        j=i;
        while(j%5==0)
        {
            count++;
            j/=5;
        }
        sum+=count;
    }
    printf("%lld\n",sum);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42217376/article/details/81302008
今日推荐