Search code examples
c++mathinteger-overflow

How can I calculate the tens place value of 2^100 in C++?


How can I calculate the tens place value of 2^100 in C++?

I tried this;

#include <cmath>
#include <iostream>

using namespace std;

int main(){
    int answer;
    answer = (unsigned long long int)pow(2, 100) % 100 / 10; //zero
    cout << answer << endl;
    return 0;
}

But it printed 0 because of overflow.

Python prints the answer correctly with this code;

print(2 ** 100 % 100 // 10)

But how do I calculate it in C++?


Solution

  • You have a problem with typecasting.

    As you can see from documentation std::pow return double

    So first step to solve our problem, try to remove type casting.

    std::pow(2, 100); // return 1.26765e+30
    

    The next problem we can't use operator % with double type so we need std::fmod So final solution would look like this:

    int answer = std::fmod(std::pow(2, 100), 100) / 10;