Project Euler的这次尝试在第16位数后失败。

时间:2012-11-05 21:38:28

标签: c++ optimization

找到2 ^ 1000

的数字之和

使用函数,用户输入base和exponent,例如4 ^ 5(base 4,exponent 5)。

如果比较矢量中输出的值和数字,则从第16位开始失败。

我的尝试:

#include<iostream>
#include<cmath>
#include<vector>
using namespace std; 


double Integer() {
    double m,o;  
    double n; 

    cout<<"Enter Base: ";
    cin>>m; 
    cout<<"Enter Exponent: ";
    cin>>o; 

    n= pow(m,o);

    cout.precision(302); 

    cout << "The Answer is: " << n << endl; 

    return n;
}

void SumoftheDigits(double n) { 

    double x, q, w=0, r, d;
    int length = r = (log(n)/ log(10)) + 1;

    vector<double> v1;

    modf((n/pow(10,r)),&x);

    while (r != 0) {

        q = modf( (n/pow(10,r-1)), &x);
        n -= x*pow(10,r-1);

        r--;
        d = x;

        v1.push_back(d);

    }

    for(vector<double>::iterator it = v1.begin(); it != v1.end(); ++it){
            cout << *it << " ";
    } 

    cout << endl; 

    int i;
    long long int Sum = 0; 

    while (i != v1.size()) {
        Sum += v1[i]; 
        i++;
    } 

    cout << "The Sum of the Digits is: " << Sum << endl; 

} 

int main() {

    double n = Integer(); 

    SumoftheDigits(n); 

    return 0;
}

1 个答案:

答案 0 :(得分:3)

浮点类型(例如floatdouble)的精度有限,因此您无法使用它们来计算大数,例如大约2 ^ 1000的值。你看到会有不准确之处。

您需要使用整数方法来执行此操作。正常整数不能表示大小为2 ^ 1000的数字,因此需要更多的工作。例如,您可以在数组中分别表示每个数字,并实现您在学校学到的长乘法。

还有一些像GMP这样的库可以代表非常大的整数(仅受计算机内存的限制),这将使这个任务变得简单。

相关问题