Program to calculate pow(x,n) using math.log2() and ** operator
Here, we can use the math.log2() in combination with the operator “**” to calculate the power of a number.
Below is the implementation of the above approach.
C++
#include <cmath> #include <iostream> using namespace std; int calculatePower( int a, int n) { return round( pow (2, (log2(a) * n))); } int main() { int a = 2; int n = 3; cout << calculatePower(a, n) << endl; return 0; } |
Output
8
Time Complexity: O(1)
Auxiliary Space: O(1)
Please refer complete article on Write program to calculate pow(x, n) for more details!
C++ Program To Calculate the Power of a Number
Write a C++ program for a given two integers x and n, write a function to compute xn. We may assume that x and n are small and overflow doesn’t happen.
Examples :
Input : x = 2, n = 3
Output : 8Input : x = 7, n = 2
Output : 49
Contact Us