大数阶乘
Time Limit:3000MS Memory Limit:65535K
Total Submit:154 Accepted:64
Description
我们都知道如何计算一个数的阶乘,可是,如果这个数很大呢,我们该如何去计算它并输出它?
Input
输入一个整数m( 0 < m < =5000)
Output
输出m的阶乘,并在输出结束之后输入一个换行符
Sample Input
50
Sample Output
30414093201713378043612608166064768844377641568960512000000000000
Hint
C 用数组
Java 用BigInteger
Source
NYIST
#include<stdio.h>
int a[1000001];
int main()
{
int n;
scanf("%d",&n);
int len=1;
a[1]=1;
for(int i=2; i<=n; ++i)
{
int b=0;
for(int j=1; j<=len; ++j)
{
int t=a[j]*i+b;
a[j]=t%10;
b=t/10;
if(j==len&&b!=0)
len++;
}
}
for(int i=len; i>0; --i)
printf("%d",a[i]);
printf("\n");
}
#include<stdio.h>
#include<string.h>
#define N 1200
int A[N];
int main()
{
int n,i,j,temp,start,sc;
while(1==scanf("%d",&n))
{
memset(A,0,sizeof(A));
for(A[0]=1,i=1; i<=n; i++)
for(sc=0,j=0; j<N; j++)
temp=A[j]*i+sc,
sc=temp/10,
A[j]=temp%10;
for(start=N-1; A[start]==0; --start);
for(; start>=0; --start)
printf("%d",A[start]);
printf("\n");
}
}
#include<iostream>//最优代码
#include<iomanip>
using namespace std;
//存储20000以内的阶乘
int a[15470];
int main()
{
//freopen("1.txt","r",stdin);
//freopen("2.txt","w",stdout);
int n;
cin>>n;
a[1]=1;
a[0]=1;
int up;
for(int i=2;i<=n;++i)
{
up=0;
for(int j=1;j<=a[0];++j) //各个位相乘
{
a[j] *=i;
a[j] +=up;
up=a[j]/100000;
a[j] %=100000;
}
if(up!=0)
{
a[0]++;
a[a[0]]=up;
}
}
if(a[0]==1) cout<<a[1];
else
{
cout<<a[a[0]];
for (int i=a[0]-1;i>0;i--)
{
cout<<setfill('0')<<setw(5)<<a[i];
}
}
}
import java.math.BigInteger;
import java.util.Scanner;
public class ny28 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int a = input.nextInt();
BigInteger s = BigInteger.valueOf(1);
for ( int i = 1;i<=a ; i++)
{
s = s.multiply(BigInteger.valueOf(i));
}
System.out.println(s);
}
}