【题解】阶乘问题

题目描述

        阶乘的定义如下:N!=1×2×3×...×N-1×N

        例如,12!=1×2×3×4×5×6×7×8×9×10×11×12=479001600

        最右的非0位是6,后面有2个0。

        写一个程序计算N!最右非0位和末尾0的个数。

输入输出格式

输入格式

        一行,一个整数N。(1≤N≤1000000)

 

输出格式

        一行,输出2个整数:最右非0位,末尾0的个数。

 

输入输出样例

输入样例

12

 

输出样例

6 2

 

题解

        因为10的约数只有1,2,5,10,则在所有不为10的正整数中,只有2与5相乘能得到10。

        我们可以枚举[1,N],得到质因子2和5的数量,从而得到10的数量,即末尾0的数量。再将剩余的因子相乘取末尾,即可得到最右边的非0位。

#include <iostream>

using namespace std;

int n;
int cnt0, cnt2, cnt5;
int ans = 1;

int main()
{
    cin >> n;
    int tmp;
    for(register int i = 1; i <= n; ++i)
    {
        tmp = i;
        while(!(tmp & 1)) tmp >>= 1, ++cnt2;
        while(!(tmp % 5)) tmp /= 5, ++cnt5;
        ans *= tmp;
        ans %= 10;
    }
    cnt0 = min(cnt2, cnt5);
    cnt2 -= cnt0;
    cnt5 -= cnt0;
    while(cnt2--)
    {
        ans <<= 1;
        ans %= 10;
    }
    while(cnt5--)
    {
        ans *= 5;
        ans %= 10;
    }
    cout << ans << " " << cnt0;
    return 0;
}
参考程序

猜你喜欢

转载自www.cnblogs.com/kcn999/p/10351028.html