zoukankan      html  css  js  c++  java
  • 4.n的高精度阶乘---优化

    题目:对于每组测试数据,在一行中给出一非负整数n(n小于等于100)

    样例输入

    3
    5
    10
    

    样例输出

    6
    120
    3628800
    
    超时的代码如下:
    #include <iostream>
    #include <cstring>
    using namespace std;

    int main(){
        int n, count = 0;
        int a[100] = {1};
        cin >> n;
        if(n == 0){
            cout << 1;
            return 0;
        }
        for(int i = n; i >= 1; i--){
            for(int j = 0; j <= count; j++){
                a[j] *= i;
            }
            for(int j = 0; j <= count; j++){
                if(a[j] > 10){    
                    while(a[j] >= 10){
                        a[j] -= 10;
                        a[j + 1]++;
                    }
                }
            }
            while(a[count]){
                count++;
            }
            
        }
        for(int i = count - 1; i >= 0; i--)
            cout << a[i];
        return 0;
    }
    上面代码最多只能跑出18的阶乘。
    下面的代码是可行的
    #include <iostream>
    using namespace std;

    int main(){
        int a[1000] = {1};
        int len = 1;
        int n, q = 0;
        cin >> n;
      if(n == 0){ //注意0的阶乘是1
        cout << 1;
        return 0;
    }
        for(int i = 1; i <= n; i++){
            q = 0; //每次要置零
            for(int j = 0; j < len; j++){
                a[j] = a[j] * i + q;
                q = a[j] / 10;
                a[j] = a[j] % 10;
            }
            if(q > 0){
                a[len] += q; //加上退出前进位
                len++;
            }
        }
        for(int i = len - 1; i >= 0; i--)
            cout << a[i];
        return 0;
    }
  • 相关阅读:
    定时器
    自定义个性化 EditPeople控件
    infopath 2010 调试.
    MOSS 查询
    网站项目建设流程概述
    跨站点显示列表数据 ListViewWebPart
    VIM记事——大小写转换
    事务码记录 程序优化常用st12
    SAP各模块字段与表的对应关系
    固定资产一览
  • 原文地址:https://www.cnblogs.com/zhumengdexiaobai/p/7291735.html
Copyright © 2011-2022 走看看