Factorial! You Must be Kidding!!!(ICPC冬令营集训题目)

Factorial! You Must be Kidding!!!

Problem Description

Arif has bought a super computer from Bongobazar. Bongobazar is a place in Dhaka where second hand goods are found in plenty. So the super computer bought by him is also second hand and has some bugs. One of the bugs is that the range of unsigned long integer of this computer for C/C++ compiler has changed. Now its new lower limit is 10000 and upper limit is 6227020800. Arif writes a program in C/C++ which determines the factorial of an integer. Factorial of an integer is defined recursively as:
factorial(0) = 1
factorial(n) = n ∗ factorial(n − 1).
Of course one can manipulate these expressions. For example, it can be written as
factorial(n) = n ∗ (n − 1) ∗ factorial(n − 2)
This definition can also be converted to an iterative one.
But Arif knows that his program will not behave rightly in the super computer. You are to write program which will simulate that changed behavior in a Normal Computer.

Input

The input file contains several lines of input. Each line contains a single integer n. No integer has more than six digits. Input is terminated by end of file.

Output

For each line of input you should output a single line. This line will contain a single integer n! if the value of n! fits within the unsigned long integer of Arif’s computer. Otherwise the line will contain one of the following two words Overflow! (When n! > 6227020800) Underflow! (When n! < 10000)

  • 输入
  • 输入包含若干行,每行给出一个整数n。不会有整数超过6位。输 入以EOF结束。
  • 输出
  • 对于每一行的输入,输出一行。如果n!的值在Arif 计算机的无符 号长整数范围内,输出行给出n!的值;否则输出行给出如下两行 之一:
  • ​ Overflow! //(当 n! > 6227020800)
  • ​ Underflow! //(当 n! < 10000)
Sample Input
2
10
100
123
Sample Output
Underflow!
3628800
Overflow!
123
Analysis of Test Questions

离线打表出20以内的阶乘数据:

#include<iostream>
#include<cstdio>

using namespace std;

int main(){
    long long sum=1;
    for(int i=1;i<20;i++){

        sum*=i;
        printf("%d = %lld\n",i,sum);
    }
    return 0;
}

输出:

1 = 1
2 = 2
3 = 6
4 = 24
5 = 120
6 = 720
7 = 5040
8 = 40320
9 = 362880
10 = 3628800
11 = 39916800
12 = 479001600
13 = 6227020800
14 = 87178291200
15 = 1307674368000
16 = 20922789888000
17 = 355687428096000
18 = 6402373705728000
19 = 121645100408832000
12345678910111213141516171819
  • 发现只有8<=n<=13满足条件;

  • 当n>13时Overflow!;

  • 当0<n<8时Underflow!;

    image-20210126213956745 所以n<0时,

    n为奇数Overflow!

    n为偶数Underflow!

AC代码
#include<iostream>
#include<cstdio>

using namespace std;

int main(){
    long long f[14];
    f[1]=1;
    long long sum=1;
    for(int i=2;i<14;i++){

        f[i]=i*f[i-1];
    }
    int n;
    while(cin>>n){
        if(n<=13&&n>=8)cout<<f[n]<<endl;
        if(n>=0&&n<=7)cout<<"Underflow!"<<endl;
        if(n>=14)cout<<"Overflow!"<<endl;
        if(n<0&&(-n)%2==1)cout<<"Overflow!"<<endl;
        if(n<0&&(-n)%2==0)cout<<"Underflow!"<<endl;
    }
    return 0;
}
posted @ 2021-01-26 22:19  独苍  阅读(120)  评论(0编辑  收藏  举报