I am trying to solve the Project Euler Problem #16: https://projecteuler.net/problem=16. It requires me to sum up every digits from the result of 2^1000.
I iterate through the string (converted from double type) by treating the string as an array. However when I try to convert string digit back to int, I always got error.
I tried with stoi, It prompts me "no matching function for call to 'atoi'". I also tried with stringstream for conversion, it still did not work.
Please see my following code:
#include <iostream>
#include <complex> // pow
#include <string> // to_string C++ 11
const double NUM = pow(2, 1000);
int main(int argc, char const *argv[]) {
int sum = 0;
//printf("%.0f\n", NUM); // Remove decimal digits
auto str = std::to_string(NUM);
std::string str_trim = str.substr(0, str.length()-7);
std::cout << str_trim << std::endl; // 2^1000 in string
for (int i = 0; i <= str_trim.length(); i++) {
std::cout << str_trim[i] << std::endl;
sum = sum + str_trim[i];
std::cout << sum << std::endl;
}
return 0;
}
Any idea to solve this problem? Thank you.
2^1000the approach, amazingly enough, works fine. The reason is that ieee754 double format will lose precision by considering missing bits to be zeros... and in 2^1000 all bits (except MSB) are zeros.