問題描述
一個整數n的階乘可以寫成n!,它表示從1到n這n個整數的乘積。階乘的增長速度非常快,例如,13!就已經比較大了,已經無法存放在一個整型變量中;而35!就更大了,它已經無法存放在一個浮點型變量中。因此,當n比較大時,去計算n!是非常困難的。幸運的是,在本題中,我們的任務不是去計算n!,而是去計算n!最右邊的那個非0的數字是多少。例如,5!=12345=120,因此5!最右邊的那個非0的數字是2。再如,7!=5040,因此7!最右邊的那個非0的數字是4。再如,15!= 1307674368000,因此15!最右邊的那個非0的數字是8。請編寫一個程序,輸入一個整數n(0<n<=100),然後輸出n!最右邊的那個非0的數字是多少。
輸入:
7
輸出:
4
#include <iostream>
using namespace std;
#include<stdio.h>
#include<stdlib.h>
#include<cstring>
#include<math.h>
int main()
{
int n;//0<=n<=100
cin>>n;
long long temp=1;
if(n<=1){
cout<<1;
return 0;
}
for(int i=2;i<=n;i++){
temp=temp*i;
while(temp%10==0){
temp=temp/10;
}
//int a=temp%10; //對該階乘數保留後三位尾數 t=c*100+b*10+a;也可四位
//temp/=10;
//int b=temp%10;
//temp/=10;
//int c=temp%10;
//temp=c*100+b*10+a;
temp=temp%10000;
}
temp=temp%10;
cout<<temp;
return 0;
}