P0505

一个整数n的阶乘可以写成n!,它表示从1到n这n个整数的乘积。阶乘的增长速度非常快,例如,13!就已经比较大了,已经无法存放在一个整型变量中;而35!就更大了,它已经无法存放在一个浮点型变量中。因此,当n比较大时,去计算n!是非常困难的。幸运的是,在本题中,我们的任务不是去计算n!,而是去计算n!最右边的那个非0的数字是多少。例如,5!=1*2*3*4*5=120,因此5!最右边的那个非0的数字是2。再如,7!=5040,因此7!最右边的那个非0的数字是4。再如,15!= 1307674368000,因此15!最右边的那个非0的数字是8。请编写一个程序,输入一个整数n(0<n<=100),然后输出n!最右边的那个非0的数字是多少。
输入:
  7
输出:
  4

成绩末尾的0由2和5产生,记录乘积中有几个2和5去掉以后,排着乘然后取个位数即可。

代码:

#include <iostream>
#include <cstdio>
#include <vector>
#include <cstdlib>
#include <cstring>
#define inf 0x3f3f3f3f
using namespace std;

int n;
int d = 1,t,f;
int main() {
    scanf("%d",&n);
    for(int i = 2;i <= n;i ++) {
        int e = i;
        while(e % 2 == 0) {
            e /= 2;
            t ++;
        }
        while(e % 5 == 0) {
            e /= 5;
            f ++;
        }
        d = (d * e) % 10;
    }
    for(int i = 0;i < t - f;i ++) {
        d = d * 2 % 10;
    }
    printf("%d",d);
}

猜你喜欢

转载自www.cnblogs.com/8023spz/p/10433042.html