加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

hdu1042-N!(大数)

发布时间:2020-12-14 02:24:10 所属栏目:大数据 来源:网络整理
导读:N! Time Limit: 10000/5000 MS (Java/Others)????Memory Limit: 262144/262144 K (Java/Others) Total Submission(s): 65262????Accepted Submission(s): 18665 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): 65262????Accepted Submission(s): 18665

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
?

这题我写的时候大部分都会超时,最后网上看了好多,才优化到2000多ms!


在写这篇博客的时候,我问了下学长,他说他900多,当时我就崩溃了,原来他是用G++提交的!


看下代码吧!


没有优化的:

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int a[36000];
int main()
{
    int n,i,j,c;
    while(scanf("%d",&n)!=EOF)
    {
        memset(a,sizeof(a));
        a[0]=1;
        for(i=2;i<=n;i++)
        {
            c=0;
            for(j=0;j<36000;j++)
            {
                a[j]=a[j]*i+c;
                c=a[j]/10;
                a[j]%=10;
            }
        }
        for(i=36000-1;a[i]==0&&i>=0;i--);
        if(i>=0)
        for(j=i;j>=0;j--)
        printf("%d",a[j]);
        printf("n");
    }
    return 0;
 }


优化后:


#include<stdio.h>
#include<string.h>
int a[36000];
int main()
{
	int n,c,temp,cot;
	while(scanf("%d",&n)!=EOF)
	{
		//memset(a,sizeof(a));
		a[0]=1;
		cot=1;
		for(i=2;i<=n;i++)
		{
			c=0;
			for(j=0;j<cot;j++)
			{
				temp=a[j]*i+c;
				c=temp/10;
				a[j]=temp%10;
			}
			while(c)
			{
				a[cot++]=c%10;
				c/=10;//cot用来记录进位
			}
		}
		for(j=cot-1;j>=0;j--)
		printf("%d",a[j]);
		printf("n");
	}
	return 0;
 }


后来学长又给了一种方法,300ms左右,谢谢康神教导!


就是数组的一个存5位!



上代码:

#include<stdio.h>
#include<string.h>
long long a[36000];
int main()
{
	int n,cot;
	int temp;
	while(scanf("%d",&n)!=EOF)
	{
		a[0]=1;
		cot=1;
		for(i=2;i<=n;i++)
		{
			c=0;
			for(j=0;j<cot;j++)
			{
				a[j]=a[j]*i+c;
				c=a[j]/100000;//每次存5位
				a[j]=a[j]%100000;
			}
			if(c>0)
			{
				a[cot]=c;
				cot++;
			}
		}
		printf("%lld",a[cot-1]);
		for(j=cot-2;j>=0;j--)
		printf("%05lld",a[j]);
		printf("n");//因为最后面的也就是最高位不需要补0,而其他位不够5位的一定要补够才行,底下这种输出,都没补0,所以会wa
//		for(j=cot-1;j>=0;j--)
//		printf("%lld",a[j]);
//		printf("n");
	}
	return 0;
 }

(编辑:李大同)

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

    推荐文章
      热点阅读