加入收藏 | 设为首页 | 会员中心 | 我要投稿 PHP编程网 - 黄冈站长网 (http://www.0713zz.com/)- 数据应用、建站、人体识别、智能机器人、语音技术!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2021-03-14 10:08:41 所属栏目:大数据 来源:网络整理
导读: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! ?

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,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,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;
}

(编辑:PHP编程网 - 黄冈站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读