0
点赞
收藏
分享

微信扫一扫

计算 n! 中末尾0的个数 求n!中p的重数


题意:

输入正整数n,计算 n! 中末尾0的个数

输入:输入一个正整数n (1≤n≤1 000 000 000)

输出:输出 n! 末尾0的个数

样例输入:3

                            100

                            1024

样例输出:0

                            24

                            253

分析:

直接计算结果很容易溢出,考虑到相乘能产生零的情况只有2*5,所以我们可以将问题转化为查找因子2、5的出现次数,取两者最小的即可。

依据定理:n! 的素因子分解中的素数p的指数(幂)为【n/p+n/p^2+n/p^3+.......

补充:对于n!,在因式分解中,因子2的个数大于5的个数,所以如果存在一个因子5,那么它必然对应着n!末尾的一个0。(只求5的指数即可)

代码实现:

#include<cstdio>  
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<cmath>
#include<iostream>
#include<sstream>
#include<iterator>
#include<algorithm>
#include<string>
#include<vector>
#include<map>
using namespace std;
const double eps = 1e-8;
typedef long long ll;
typedef unsigned long long ULL;
const int INF = 0x3f3f3f3f;
const int INT_M_INF = 0x7f7f7f7f;

const int dr[] = {0, 0, -1, 1, -1, -1, 1, 1};
const int dc[] = {-1, 1, 0, 0, -1, 1, -1, 1};
const int MOD = 1e9 + 7;
const double pi = acos(-1.0);
const int MAXN=5010;
const int MAXM=100010;
const int M=50010;
ll cal(ll n,ll p)
{
ll num=0;
while (n)
{
num += n/p;
n=n/ p;
}
return num;
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
printf("%d\n",min(cal(n,2),cal(n,5)));
}
return 0;
}

 

举报

相关推荐

0 条评论