现在的位置: 首页 > 综合 > 正文

joj 1386解题报告

2014年03月12日 ⁄ 综合 ⁄ 共 2111字 ⁄ 字号 评论关闭
文章目录

 

 1386: 500!


Result TIME Limit MEMORY Limit Run Times AC Times JUDGE
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;
}

 

 

抱歉!评论已关闭.