hdu1042-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,0,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,i,j,c,temp,cot;
	while(scanf("%d",&n)!=EOF)
	{
		//memset(a,0,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,i,j,c,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;
 }



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值