您的位置:首页 > 职场人生

程序员面试金典——解题总结: 9.17中等难题 17.3设计一个算法,算出n阶乘有多少个尾随0

2017-01-16 14:28 411 查看
#include <iostream>
#include <stdio.h>

using namespace std;

/*
问题:设计一个算法,算出n阶乘有多少个尾随0
分析: 发现凡是n!中寻找出1~n中5的倍数的5的指数累加和k,即为有多少个尾随0,
5! 有1个0,
10! 有2个0
15! 有..
25 = 5*5,有2个0
125=5^3,有3个0
注意阶乘的结果可能溢出
输入:
20
输出:
5

关键:
1 n阶乘有多少个尾随0 = 求1到n中,有多少个5的倍数
2 球n中有几个m的倍数,直接讲n除以m
//直接数一数:5的倍数,25的倍数,125的倍数:比如25,有5个5的倍数,有1个25的倍数,共6个,25刚好多的5被等效认为是25的倍数有1个
int countFactorialZero(int n)
{
int count = 0;
for(int i = 5 ; n / i > 0 ; i *= 5)
{
count += n / i;
}
return count;
}
*/

int getZeroTimes(int n)
{
int count = 0;
int temp ;
for(int i = 5 ; i <= n; i += 5)
{
temp = i;
while(temp >= 5)
{
temp /= 5;
count++;
}
}
return count;
}

//直接数一数:5的倍数,25的倍数,125的倍数:比如25,有5个5的倍数,有1个25的倍数,共6个,25刚好多的5被等效认为是25的倍数有1个
int countFactorialZero(int n)
{
int count = 0;
for(int i = 5 ; n / i > 0 ; i *= 5)
{
count += n / i;
}
return count;
}

void process()
{
int n;
while(cin >>n)
{
//int result = getZeroTimes(n);
int result = countFactorialZero(n);
cout << result << endl;
}
}

int main(int argc , char* argv[])
{
process();
getchar();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐