题目描述
此题题意是重新规定了整数的范围,在计算时需要注意数的范围,否则会tle
注意:需要考虑负数
#include<iostream>
using namespace std;
int main(){
int n;
while(cin>>n){
if(n<0){
if(n%2==0)
cout<<"Underflow!"<<endl;
else
cout<<"Overflow!"<<endl;
}
else
{
long long sum=1;
for(int i=1;i<=n;i++){
sum*=i;
if(sum>6227020800)
break;
}
if(sum<10000)
cout<<"Underflow!"<<endl;
else if(sum>6227020800)
cout<<"Overflow!"<<endl;
else
cout<<sum<<endl;
}
}
return 0;
}
此题也可以采取打表的方法计算出符合条件的N的范围,大佬的代码
/* UVA10323 Factorial! You Must be Kidding!!! */
#include <bits/stdc++.h>
//#define DEBUG
using namespace std;
const long long FACT1 = 10000;
const long long FACT2 = 6227020800;
const int N = 13;
long long fact[N + 1];
void init()
{
fact[0] = 1;
for(int i=1; i<=N; i++) {
fact[i] = i * fact[i - 1];
#ifdef DEBUG
if(fact[i] > FACT2) {
printf("N=%d\n", i - 1);
break;
}
#endif
}
}
int main()
{
init();
int n;
while(~scanf("%d", &n))
if(n > N || (n < 0 && (n * -1 & 1)== 1))
printf("Overflow!\n");
else if(fact[n] < FACT1 || (n < 0 && (n * -1 & 1) == 0))
printf("Underflow!\n");
else
printf("%lld\n", fact[n]);
return 0;
}