2017.10.30

题目描述

输入一个正整数n,求n!(即阶乘)末尾有多少个0? 比如: n = 10; n! = 3628800,所以答案为2

输入描述:

输入为一行,n(1 ≤ n ≤ 1000)

输出描述:

输出一个整数,即题目所求
示例1

输入

10

输出

2


解题思路就是把所有的数字进行分解质因数,例如:
6 = 2*3
15 = 3*5
64 = 2*2*2*2*2*2 = 2^6
100 = 2^2 * 5^2
576 = 2^6 * 3^2
那么我们在计算n的阶乘时,实际上就是把所有小于等于n的正整数分解成质因数,然后再将其乘到一起,那么末尾0的个数实际上就是2*5的个数,而2的个数明显是很多很多的,所以问题就转化成了5的个数。
而只有5的倍数才有5这个因数,所以,问题就进一步简化为小于等于n的数中有多少个数是5的倍数,当然25的倍数,125的倍数,625还要单独考虑。
 
 
 

#include <iostream>
#include <stdio.h>
#include <math.h>
#include <iomanip> //不能写成#include <iomanip.h>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char** argv)
{
int n;
int num;
int zero_num=0;
int temp;
scanf("%d",&n);
for(int k=1;k<n+1;k++)
{
temp=k;
num=0;
while((temp>=5)&&(temp%5==0))
{
num++;
temp=temp/5;
}
zero_num+=num;
}

cout<<zero_num<<endl;
return 0;
}

原文地址:https://www.cnblogs.com/panlangen/p/7758138.html