#include <iostream>
using namespace std;
int getZeroNum(int n) {
int count = 0;
for (int i = 1; i <= n; i++) {
int j = i;
while (j%5 == 0) {
++count;
j /= 5;
}
}
return count;
}
//利用Z=[N/5] + [N/5*5] + ...的性质
int getZeroNum1(int n) {
int count = 0;
while (n) {
count += n/5;
n /= 5;
}
return count;
}
// 计算n!的末尾1的个数
// 首先所有的奇数各位上都是1,那么所有的奇数相乘之后的结果各位还是1
// 然后每乘以2就相当于将各位的1往前移了一步,那么最后的结果转换为求n!中2因子的个数
// 利用Z=[N/2] + [N/2*2] + ...的性质
int getOneIndex(int n) {
int count = 1;
while (n) {
n >>= 1;
count += n;
}
return count;
}
//最后还有一条规律就是N中质因数2的个数还等于N - N中1的个数
//那么问题就转换成求N中1的个数了,可参见博文
//http://blog.csdn.net/shen823797837/article/details/8426553
int main() {
int n = 100;
cout << getZeroNum(n) << endl;
cout << getZeroNum1(n) << endl;
cout << getOneIndex(3) << endl;
return 0;
}
[编程之美]不要被阶乘吓倒
最新推荐文章于 2017-05-22 16:21:16 发布