1172:求10000以内n的阶乘

1172:求10000以内n的阶乘

时间限制: 1000 ms 内存限制: 65536 KB
提交数: 6575 通过数: 1675
【题目描述】
求10000以内n的阶乘。

【输入】
只有一行输入,整数n(0≤n≤10000)。

【输出】
一行,即n!的值。

【输入样例】
4
【输出样例】
24

没有优化,直接爆掉了。
信息学奥赛一本通oj平台,最后两组数据没有过。
记录一下。
#include<bits/stdc++.h>
using namespace std;
int c[40000];
int main(){
	c[1]=1;
	int n;
	cin>>n;
	int t=n;
	int j=1;
	while(n--){	
	   int temp=0;
	   int i;
	   for(i=1;i<=40000;i++){
	   	c[i]=j*c[i]+temp;
	   	temp=c[i]/10;
	   	c[i]=c[i]%10;
	   } 
	   j++;
	   //c[i]=temp;
	}
	int index=0;
	for(int i=40000;i>0;i--){
		if(c[i]){
			index=i;
			break;
		}
	}
	for(int i=index;i>0;i--)
	cout<<c[i];
	cout<<endl;
	return 0;
} 


时刻记着最高位height,减少很多的遍历时间
#include<bits/stdc++.h>
using namespace std;
int c[40000];
int main(){
	c[1]=1;
	int n;
	cin>>n;
	int j=1;
	int height=1;//最高位 
	while(n--){	
	   int temp=0;
	   int i;
	   for(i=1;i<=height;i++){
	   	c[i]=j*c[i]+temp;
	   	temp=c[i]/10;
	   	c[i]=c[i]%10;
	   } 
	   j++;
	    while(temp){
			c[++height]=temp%10;
			temp/=10;
		}
	  
	}
	for(int k=height;k>0;k--){
		cout<<c[k];
	}
	cout<<endl;
	return 0;
} 


在上一次超时代码的基础上进行优化:
#include<bits/stdc++.h>
using namespace std;
int c[40000];
int main(){
	c[1]=1;
	int n;
	cin>>n;
	int j=1;
	int height=1;//最高位 
	while(n--){	
	   int temp=0;
	   int i;
	   for(i=1;i<=height;i++){
	   	c[i]=j*c[i]+temp;
	   	temp=c[i]/10;
	   	c[i]=c[i]%10;
	   } 
	   j++;
	    while(temp){
			c[++height]=temp%10;
			temp/=10;
		}
	  
	}
	for(int k=height;k>0;k--){
		cout<<c[k];
	}
	cout<<endl;
	return 0;
} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值