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)0/10;//zero
cout<<answer<<endl;
return 0;
}
But it printed 0 because of overflow.
Python prints the answer correctly with this code;
print(2**1000//10)
But how do I calculate it in C ?
CodePudding user response:
Just do it in 2 steps:
int x = (1<<25)0;
x = (x*x*x*x)0;
x = x/10;
CodePudding user response:
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
}
CodePudding user response:
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;