zoukankan      html  css  js  c++  java
  • UVa10323:Factorial! You Must be Kidding!!!

    UVa10323:Factorial! You Must be Kidding!!!


    题目大意


    给定数字n,计算n!并输出。有两个特例,如果n!超过6227020800则输出Overflow!,如果n!小于10000则输出Underflow!

    Solution


    6227020800刚好是13!,而10000介于7!和8!之间,所以只要对n做一下比较,分情况输出即可。

    Note


    这题有个很智障的地方——n可以为负数。所以需要强行拓展关于阶乘的定义。

    factorial(n) = n ∗ factorial(n − 1)

    利用题目中给出的这个公式,factorial(0) = 0 ∗ factorial(-1)
    再稍作变形factorial(-1) = factorial(0) / 0,所以-1的阶乘等于∞。继续按照这个思路扩展,factorial(-1) = -1 ∗ factorial(-2),所以-2的阶乘等于-∞。

    以此类推,在n为负数的前提下,n如果是奇数答案就是Overflow!,如果是偶数答案就是Underflow!

    AC-Code(C++)


    Time:0ms

    #include <iostream>
    #include <iomanip>
    #include <algorithm>
    #include <string>
    #include <cstring>
    #include <map>
    #include <set>
    #include <vector>
    #include <cmath>
    #include <climits>
    #include <ctime>
    
    using namespace std;
    typedef long long ll;
    const int INF = 0x3f3f3f3f;
    const double PI = acos(-1.0);
    const int maxn = 1000 + 10;
    
    ll fact[20];
    
    int main(int argc, const char * argv[]) {
    
    //    freopen("input.txt", "r", stdin);
    //    freopen("output.txt", "w", stdout);
    
        // 13! = 6227020800
        // 7! < 10000 < 8!
        fact[0] = 1;
        for(int i=1;i<=13;i++)
            fact[i] = i * fact[i-1];
    
        // what the hell?
        // definition for negative number doesn't make sense at all.
        int n;
        while(scanf("%d",&n)==1){
            if(n > 13 || (n < 0 && -1*n%2 == 1))
                printf("Overflow!
    ");
            else if(n <= 7 || (n < 0 && -1*n%n == 0))
                printf("Underflow!
    ");
            else
                printf("%lld
    ",fact[n]);
        }
        return 0;
    }
    
  • 相关阅读:
    &nbsp|&quot|&amp|&lt|&gt等html字符转义
    OpenSSL: 消息摘要算法
    Linux下tcp协议socket的recv函数返回时机分析(粘包)
    ipv6
    Electron 调用系统工具记事本、计算器等
    MySQL 导出函数与存储过程
    远程连接Ubuntu桌面配置
    当Activity继承AppCompatActivity如何实现隐藏标题栏与状态栏
    spring boot 1.5.2 操作mongodb3.4.0
    VScode-Go can't load package: package .: no buildable Go source files in
  • 原文地址:https://www.cnblogs.com/irran/p/UVa10323.html
Copyright © 2011-2022 走看看