您的位置:首页 > 编程语言 > Java开发

HDU 1042 N! (大数阶乘,紫书上的方法超时!!还是Java大法好!!)

2016-05-12 23:00 579 查看


N!

Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)

Total Submission(s): 73270 Accepted Submission(s): 21210



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

JGShining(极光炫影)

原题链接:http://acm.hdu.edu.cn/showproblem.php?pid=1042

大数!还是Java大发好,刘汝佳紫书上有一道阶乘的例题,但是超时!!!具体原因看代码!



AC代码1(Java)

import java.math.BigDecimal;
import java.util.Scanner;

public class Main {

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int n = sc.nextInt();
System.out.println(fun(n));
}
}

public static BigDecimal fun(int n) {
BigDecimal s = new BigDecimal(1);
for (int i = 1; i <= n; i++) {
BigDecimal a = new BigDecimal(i);
s = s.multiply(a);
}
return s;
}

}


AC代码2(C模拟)

#include<stdio.h>
#include<string.h>
#define maxn 50000
int f[maxn];
int main()
{
int i,j,n;
while(scanf("%d",&n)!=EOF)
{
memset(f,0,sizeof(f));
f[0]=1;
int count=1;
for(i=1; i<=n; i++)
{
int c=0;//进位
for(j=0; j<count; j++)//阶乘位数
{
int s=f[j]*i+c;
f[j]=s%10;
c=s/10;
}
while(c)
{
f[count++]=c%10;
c/=10;
}
}
for(j=maxn-1; j>=0; j--)
if(f[j]) break;
for(i=j; i>=0; i--)
printf("%d",f[i]);
printf("\n");
}
return 0;
}



超时代码:

#include<stdio.h>
#include<string.h>
#define maxn 50000
int f[maxn];
int main()
{
int i,j,n;
while(scanf("%d",&n)!=EOF)
{
memset(f,0,sizeof(f));
f[0]=1;
for(i=2; i<=n; i++)
{
int c=0;
for(j=0; j<maxn; j++)//长度,每次都到最大,导致超时!!!!
{
int s=f[j]*i+c;
f[j]=s%10;
c=s/10;
}
}
for(j=maxn-1; j>=0; j--)
if(f[j]) break;
for(i=j; i>=0; i--)
printf("%d",f[i]);
printf("\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: