'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 1:[1]

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;

Solution 2:[2]

Just do it in 2 steps:

int x = (1<<25)%100;
x = (x*x*x*x)%100;
x = x/10;

Solution 3:[3]

unsigned long long int is not large enough to store 2**100. If you are using GCC or Clang, try to use __int128 instead.

#include <cmath>
#include <cstdint>
#include <iostream>
int main(int argc, char **argv) {
  int answer = ((__int128)std::pow(2, 100)) % 100 / 10;
  std::cout << answer << '\n'; // 7
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 sjaustirni
Solution 2 Matt Timmermans
Solution 3 ramsay