洛谷——P1134 階乘問題
阿新 • • 發佈:2017-11-26
div spa gif 問題 -m 計算 reg algo event
70分暴力枚舉+暴力乘法
P1134 階乘問題
題目描述
也許你早就知道階乘的含義,N階乘是由1到N相乘而產生,如:
12! = 1 x 2 x 3 x 4 x 5 x 6 x 7 x 8 x 9 x 10 x 11 x 12 = 479,001,600
12的階乘最右邊的非零位為6。
寫一個程序,計算N(1<=N<=50,000,000)階乘的最右邊的非零位的值。
註意:10,000,000!有2499999個零。
輸入輸出格式
輸入格式:
僅一行包含一個正整數N。
輸出格式:
單獨一行包含一個整數表示最右邊的非零位的值。
輸入輸出樣例
輸入樣例#1: 復制12輸出樣例#1: 復制
6
70分暴力枚舉+暴力乘法
#include<cstdio> #include<cstring> #include<iostream> #include<algorithm> #define p 1000000 #define mod 10 using namespace std; int n,l,k,f[10],sum,ans; int read() { int x=0,f=1; char ch=getchar(); while(ch<‘0‘||ch>‘9‘){if(ch==‘-‘)f=-1;ch=getchar();}70分while(ch>=‘0‘&&ch<=‘9‘) x=x*10+ch-‘0‘,ch=getchar(); return x*f; } int main() { n=read();sum=1; for(int i=1;i<=n;i++) { sum=(1ll*sum*i%p)%p; while(sum%10==0) sum/=10; } ans=sum%10; printf("%d",ans); return 0; }
#include<cstdio> #include<cstring> #include<iostream> #include<algorithm> #define p 1000000 #define mod 10 using namespace std; int n,l,k,f[10],ans; long long sum; int read() { int x=0,f=1; char ch=getchar(); while(ch<‘0‘||ch>‘9‘){if(ch==‘-‘)f=-1;ch=getchar();} while(ch>=‘0‘&&ch<=‘9‘) x=x*10+ch-‘0‘,ch=getchar(); return x*f; } int main() { n=read();sum=1; for(int i=1;i<=n;i++) { sum=1ll*sum*i; while(sum%10==0) sum/=10; sum=sum%p; } ans=sum%10; printf("%d",ans); return 0; }
洛谷——P1134 階乘問題