HDU N!
N!
Time Limit : 10000/5000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 71 Accepted Submission(s) : 20
Font: Times New Roman | Verdana | Georgia
Font Size: ← →
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
Author
Statistic | Submit | Back
思路:
1:可以考虑用字符数组,然后再每位相乘,满十进位。但我感觉,可能太慢,于是就没用此方法。
2:就是考虑到此题的特殊性,输入的数并不大,只是在计算过程中结果大,因此,考虑到了有整形数组来存储数据,超过八位数(或者四位数)就把多出来的放到一个新的数组元素中。
就是相当于100000000位进制;
输出时,按八位输出,不满八位补零。
代码:
#include <iostream>
#include<cstdio>
#include<cmath>
using namespace std;
void factorial(int n)
{
long long int a[10000];
int i,j,c,m=0;
a[0]=1;
for(i=1; i<=n; i++)
{
c=0;
for(j=0; j<=m; j++)
{
a[j]=a[j]*i+c;
c=a[j]/100000000;
a[j]=a[j]%100000000;
}
if(c>0)
{
m++;
a[m]=c;
}
}
printf("%I64d",a[m]);
for(i=m-1; i>=0; i--)
printf("%08I64d",a[i]);
printf("\n");
}
int main()
{
int n;
while(cin>>n)
factorial(n);
return 0;
}
#include<cstdio>
#include<cmath>
using namespace std;
void factorial(int n)
{
long long int a[10000];
int i,j,c,m=0;
a[0]=1;
for(i=1; i<=n; i++)
{
c=0;
for(j=0; j<=m; j++)
{
a[j]=a[j]*i+c;
c=a[j]/100000000;
a[j]=a[j]%100000000;
}
if(c>0)
{
m++;
a[m]=c;
}
}
printf("%I64d",a[m]);
for(i=m-1; i>=0; i--)
printf("%08I64d",a[i]);
printf("\n");
}
int main()
{
int n;
while(cin>>n)
factorial(n);
return 0;
}