Is Pow () calculating incorrectly?

I need to use pow in my C ++ program, and if I call the pow() function as follows:

 long long test = pow(7, e); 

Where

e is an integer value with a value of 23.

As a result, I always get 821077879 . If I calculated it using the windows calculator, I get 27368747340080916343 .. What is wrong here? ):

I tried to use different types, but nothing helped here ... What could be the reason for this? How can I use pow() correctly?

Thanks!

+4
source share
3 answers

The result does not match long long .

If you want to deal with very large numbers, use a library like GMP

Or save it as a floating point (which will not be so accurate).

Application of modulo:

 const unsigned int b = 5; // base const unsigned int e = 27; // exponent const unsigned int m = 7; // modulo unsigned int r = 1; // remainder for (int i = 0; i < e; ++i) r = (r * b) % m; // r is now (pow(5,27) % 7) 
+7
source

7 23 is too large to fit in long long (assuming it is 64 bit). The value becomes truncated.

Edit: Oh, why didn't you say you want pow(b, e) % m instead of just pow(b, e) ? This makes things a lot easier, because in the end you don't need bigints. Just do all your m arithmetic mod. Pubby's solution works, but it’s faster here (O (log e) instead of O (e)).

 unsigned int powmod(unsigned int b, unsigned int e, unsigned int m) { assert(m != 0); if (e == 0) { return 1; } else if (e % 2 == 0) { unsigned int squareRoot = powmod(b, e / 2, m); return (squareRoot * squareRoot) % m; } else { return (powmod(b, e - 1, m) * b) % m; } } 
+6
source

Watch it live: https://ideone.com/YsG7V

 #include<iostream> #include<cmath> int main() { long double ldbl = pow(7, 23); double dbl = pow(7, 23); std::cout << ldbl << ", " << dbl << std::endl; } 

Output: 2.73687e + 19, 2.73687e + 19

+4
source

Source: https://habr.com/ru/post/1381806/


All Articles