码迷,mamicode.com
首页 > 其他好文 > 详细

4.n的高精度阶乘---优化

时间:2017-08-05 22:55:46      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:测试数据   精度   i++   题目   count   sample   测试   nbsp   back   

题目:对于每组测试数据,在一行中给出一非负整数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;
}

4.n的高精度阶乘---优化

标签:测试数据   精度   i++   题目   count   sample   测试   nbsp   back   

原文地址:http://www.cnblogs.com/zhumengdexiaobai/p/7291735.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!