title: ‘阶乘 第一个不是零的数字’date: 2020-03-16 21:56:25
tags: [蓝桥杯]
published: true
hideInList: false
feature:
isTop: false

  1. /*试题 算法训练 P0505
  2. 资源限制
  3. 时间限制:1.0s 内存限制:256.0MB
  4.   一个整数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!=
  5. 1307674368000,因此15!最右边的那个非0的数字是8。请编写一个程序,输入一个整数n(0<n<=100),然后输出n!最右边的那个非0的数字是多少。
  6. 输入:
  7.   7
  8. 输出:
  9.   4
  10. */
  11. #include <iostream>
  12. using namespace std;
  13. int delZero(int i) {
  14. while (i % 10 == 0) {
  15. i /= 10;
  16. };
  17. return i;
  18. }
  19. int main() {
  20. int n;
  21. cin >> n;
  22. int ans = 1;;
  23. for (int i = 1; i <= n; i++) {
  24. ans *= i;
  25. ans = delZero(ans);
  26. ans = ans % 1000;
  27. }
  28. cout <<ans%10;
  29. return 0;
  30. }

因为这道题n的范围是 n<100 所以对1000求余是可以得出正确答案的,如果更大可以用数组模拟乘法来做

#include <iostream>
#include <string.h>
using namespace std;
int a[10005];
int main() {
    long n;
    memset(a, 0, sizeof(a));
    cin >> n;
    a[0] = 1;
    int s, c = 0;  // c 进位
    for (int i = 2; i <= n; i++) {
        for (int j = 0; j < 10000; j++) {
            s = a[j] * i + c;
            a[j] = s % 10;
            c = s / 10;
        }
    }
    for (int i = 0;; i++) {
        if (a[i] != 0) {
            cout << a[i];
            break;
        }
    }
    return 0;
}