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

来源:互联网 发布:英语点读机软件下载 编辑:程序博客网 时间:2024/05/16 18:44
#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;}

0 0
原创粉丝点击