joj 1386解題報告

 1386: 500!


ResultTIME LimitMEMORY LimitRun TimesAC TimesJUDGE
3s 8192K 2898 518 Standard

In these days you can more and more often happen to see programs which perform some useful calculations being executed rather then trivial screen savers. Some of them check the system message queue and in case of finding it empty (for examples somebody is editing a file and stays idle for some time) execute its own algorithm.

As an examples we can give programs which calculate primary numbers.

 


One can also imagine a program which calculates a factorial of given numbers. In this case it is the time complexity of order O(n) which makes troubles, but the memory requirements. Considering the fact that 500! gives 1135-digit number no standard, neither integer nor floating, data type is applicable here.

 


Your task is to write a programs which calculates a factorial of a given number.

Assumptions: Value of a number "n" which factorial should be calculated of does not exceed 500.

Input

Any number of lines, each containing value "n" for which you should provide value of n!

Output

2 lines for each input case. First should contain value "n" followed by character `!'. The second should contain calculated value n!. Mind that visually big numbers will be automatically broken after 80 characters.

Sample Input

 

10
30
50
100

Sample Output

10!
3628800
30!
265252859812191058636308480000000
50!
30414093201713378043612608166064768844377641568960512000000000000
100!
93326215443944152681699238856266700490715968264381621468592963895217599993229915
608941463976156518286253697920827223758251185210916864000000000000000000000000
這道題就是高精度階乘,將結果用數組保存,然後模擬正常筆算,注意輸出格式,每當輸出了80個字符時,若還有字符,先換行,在輸出。
代碼:
語言:c++
#include<iostream>
using namespace std;
int main()
{
int n,a[10000],len,k;
int factorial(int a[],int n);//將結果保存在數組a中,返回結果的長度-1
while(cin>>n)
{
cout<<n<<'!'<<endl;
len=factorial(a,n);
k=1;
for(i=len;i>=0;--i,++k)//k爲計數器
{
cout<<a[i];
if(k%80==0&&i)//每當輸出了80個數字且i不等於0是,輸出換行
cout<<endl;
}
cout<<endl;
}
return 0;
}
int factorial(int a[],int n)
{
int temp,high,carry,i,j;
memset(a,0,sizeof(a));//將數組a所有元素全部置爲0
a[0]=1;
if(n==0)
return 0;
else
{
high=0;//high爲結果當前的最高位,開始時爲0
for(i=1;i<=n;++i)
{
carry=0;//carry爲進位
for(j=0;j<=high;j++)//模擬筆算,a[0]爲數字的最低位
{
temp=a[j]*i+carry;
a[j]=temp%10;
carry=temp/10;
}
if(carry)//將進位的數全部除盡
{
while(carry)
{
a[j++]=carry%10;
carry/=10;
high=j-1;//確定結果當前的最高位數
}
}
}
return high;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章