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