hdu 1042 高精乘低精 高精度算法

Problem Description
Given an integer N(0 ≤ N ≤ 10000), your task is to calculate N!
 

 

Input
One N in one line, process to the end of file.
 

 

Output
For each N, output N! in one line.
 

 

Sample Input
1 2 3
 

 

Sample Output
1 2 6
 
題意:求n的階乘,只不過n的數比較大:0<n<=10000。這是一個高精度的算法,高精乘低精。計算了下10000的階乘有35660位。。。。
思路:模擬乘法計算。用數組存結果,再從數組個位取每一位數乘下一位階乘。用代碼實現。代碼以下:
#include<stdio.h> #include<string.h>
int len; int ans[60000]; void multiply(int i) { int res=0,t; for(int j=0;j<len;j++) { t=ans[j]*i+res;//res是進位
        ans[j]=t%10; res=t/10; } while(res)//最後把最後的一位乘下來的進位加到後面
 { ans[len++]=res%10; res/=10; } } int main() { int n; while(~scanf("%d",&n)) { len=1; memset(ans,0,sizeof(ans)); ans[0]=1;//初始爲1
        for(int i=2;i<=n;i++) multiply(i); for(int i=len-1;i>=0;i--) printf("%d",ans[i]); printf("\n"); } }
View Code
相關文章
相關標籤/搜索