C++ Program To Calculate the Power of a Number
Last Updated :
13 Oct, 2023
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 : 8
Input : x = 7, n = 2
Output : 49
Program to calculate pow(x, n) using Naive Approach:
A simple solution to calculate pow(x, n) would multiply x exactly n times. We can do that by using a simple for loop
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Naive iterative solution to calculate pow(x, n)
long power(int x, unsigned n)
{
// Initialize result to 1
long long pow = 1;
// Multiply x for n times
for (int i = 0; i < n; i++) {
pow = pow * x;
}
return pow;
}
// Driver code
int main(void)
{
int x = 2;
unsigned n = 3;
// Function call
int result = power(x, n);
cout << result << endl;
return 0;
}
- Time Complexity: O(n)
- Auxiliary Space: O(1)
pow(x, n) using recursion:
We can use the same approach as above but instead of an iterative loop, we can use recursion for the purpose.
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
int power(int x, int n)
{
// If x^0 return 1
if (n == 0)
return 1;
// If we need to find of 0^y
if (x == 0)
return 0;
// For all other cases
return x * power(x, n - 1);
}
// Driver Code
int main()
{
int x = 2;
int n = 3;
// Function call
cout << (power(x, n));
}
// This code is contributed by Aditya Kumar (adityakumar129)
- Time Complexity: O(n)
- Auxiliary Space: O(n) n is the size of the recursion stack
To solve the problem follow the below idea:
There is a problem with the above solution, the same subproblem is computed twice for each recursive call. We can optimize the above function by computing the solution of the subproblem once only.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
// Function to calculate x raised to the power y in O(logn)
int power(int x, unsigned int y)
{
int temp;
if (y == 0)
return 1;
temp = power(x, y / 2);
if (y % 2 == 0)
return temp * temp;
else
return x * temp * temp;
}
/*Driver code */
int main()
{
int x = 2; // Base
unsigned int y = 3; // Exponent
int result = power(x, y);
std::cout << result << std::endl;
return 0;
}
Time Complexity: O(log n)
Auxiliary Space: O(log n), for recursive call stack
Extend the pow function to work for negative n and float x:
Below is the implementation of the above approach:
C++
/* Extended version of power function
that can work for float x and negative y*/
#include <bits/stdc++.h>
using namespace std;
float power(float x, int y)
{
float temp;
if (y == 0)
return 1;
temp = power(x, y / 2);
if (y % 2 == 0)
return temp * temp;
else {
if (y > 0)
return x * temp * temp;
else
return (temp * temp) / x;
}
}
// Driver Code
int main()
{
float x = 2;
int y = -3;
// Function call
cout << power(x, y);
return 0;
}
// This is code is contributed
// by rathbhupendra
Time Complexity: O(log |n|)
Auxiliary Space: O(log |n|) , for recursive call stack
Program to calculate pow(x,n) using inbuilt power function:
To solve the problem follow the below idea:
We can use inbuilt power function pow(x, n) to calculate xn
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
int power(int x, int n)
{
// return type of pow()
// function is double
return (int)pow(x, n);
}
// Driver Code
int main()
{
int x = 2;
int n = 3;
// Function call
cout << (power(x, n));
}
// This code is contributed by hemantraj712.
Time Complexity: O(log n)
Auxiliary Space: O(1), for recursive call stack
Program to calculate pow(x,n) using Binary operators:
Some important concepts related to this approach:
- Every number can be written as the sum of powers of 2
- We can traverse through all the bits of a number from LSB to MSB in O(log n) time.
Illustration:
3^10 = 3^8 * 3^2. (10 in binary can be represented as 1010, where from the left side the first 1 represents 3^2 and the second 1 represents 3^8)
3^19 = 3^16 * 3^2 * 3. (19 in binary can be represented as 10011, where from the left side the first 1 represents 3^1 and second 1 represents 3^2 and the third one represents 3^16)
Below is the implementation of the above approach.
C++
// C++ program for the above approach
#include <iostream>
using namespace std;
int power(int x, int n)
{
int result = 1;
while (n > 0) {
if (n & 1 == 1) // y is odd
{
result = result * x;
}
x = x * x;
n = n >> 1; // y=y/2;
}
return result;
}
// Driver Code
int main()
{
int x = 2;
int n = 3;
// Function call
cout << (power(x, n));
return 0;
}
// This code is contributed bySuruchi Kumari
Time Complexity: O(log n)
Auxiliary Space: O(1)
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;
}
Time Complexity: O(1)
Auxiliary Space: O(1)
Please refer complete article on Write program to calculate pow(x, n) for more details!
Similar Reads
C++ Program to Calculate Logarithmic Gamma of a Number
Gamma Function in C++ is described as the factorial for complex and real numbers. This function is used to calculate the factorial on all complex values except for the negative values. Representation of gamma function: Î(x)=(xâ1)! It is one of the best practices to add a logarithm to the gamma funct
3 min read
C++ Program to Make a Simple Calculator
A simple calculator is a device used to perform basic arithmetic operations such as addition, subtraction, multiplication, and division. It makes arithmetic calculations easier and faster. In this article, we will learn how to code a simple calculator using C++.ExamplesInput: Enter an operator (+, -
3 min read
C++ Program to Perform Calculations in Pure Strings
Given a string of operations containing three operands for each operation "type of command", "first operand", and "second operand". Calculate all the commands given in this string format. In other words, you will be given a pure string that will ask you to perform an operation and you have to perfor
5 min read
C++ Program to Find Factorial of a Large Number Using Recursion
Given a large number N, task is to find the factorial of N using recursion. Factorial of a non-negative integer is the multiplication of all integers smaller than or equal to n. For example factorial of 6 is 6*5*4*3*2*1 which is 720. Examples: Input : N = 100Output : 93326215443944152681699238856266
2 min read
C++ Program To Multiply Two Floating-Point Numbers
Here, we will see how to multiply two floating-point numbers using the C++ program. Floating point numbers are numbers that include both integer part and fractional parts represented in the form of decimal and exponential values. float data type is used to store floating point values. For example In
2 min read
C++ Program to Find Factorial of a Number Using Iteration
Factorial of a number n is the product of all integers from 1 to n. In this article, we will learn how to find the factorial of a number using iteration in C++. Example Input: 5Output: Factorial of 5 is 120Factorial of Number Using Iteration in C++To find the factorial of a given number we can use l
2 min read
C++ Program to Find Factorial of a Number Using Dynamic Programming
The Factorial of a number N can be defined as the product of numbers from 1 to the number N. More formally factorial of n can be defined by function,f(n) = 1 \times 2 \times 3 \times... \ nIn this article, we will learn how to find the factorial of a number using dynamic programming in C++.Example:I
2 min read
Find all powers of 2 less than or equal to a given number
Given a positive number N, the task is to find out all the perfect powers of two which are less than or equal to the given number N. Examples: Input: N = 63 Output: 32 16 8 4 2 1 Explanation: There are total of 6 powers of 2, which are less than or equal to the given number N. Input: N = 193 Output:
6 min read
Distinct powers of a number N such that the sum is equal to K
Given two numbers N and K, the task is to print the distinct powers of N which are used to get the sum K. If it's not possible, print -1. Examples: Input: N = 3, K = 40 Output: 0, 1, 2, 3 Explanation: The value of N is 3. 30 + 31 + 32 + 33 = 40 Input: N = 4, K = 65 Output: 0, 3 The value of N is 4.
14 min read
C++ Program to Print Armstrong Numbers Between 1 to 1000
Here, we will see how to print Armstrong numbers between 1 to 1000 using a C++ program. Armstrong Number A number "N" is an Armstrong number if "N" is equal to the sum of all N's digits raised to the power of the number of digits in N. Example: There are 2 ways to find all the Armstrong numbers betw
3 min read