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++ Programming Language C++ is a computer programming language developed by Bjarne Stroustrup as an extension of the C language. It is known for is fast speed, low level memory management and is often taught as first programming language. It provides:Hands-on application of different programming concepts.Similar syntax to
5 min read
Object Oriented Programming in C++ Object Oriented Programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so th
5 min read
Inheritance in C++ The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object-Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the informatio
10 min read
30 OOPs Interview Questions and Answers [2025 Updated] Object-oriented programming, or OOPs, is a programming paradigm that implements the concept of objects in the program. It aims to provide an easier solution to real-world problems by implementing real-world entities such as inheritance, abstraction, polymorphism, etc. in programming. OOPs concept is
15 min read
Vector in C++ STL C++ vector is a dynamic array that stores collection of elements same type in contiguous memory. It has the ability to resize itself automatically when an element is inserted or deleted.Create a VectorBefore creating a vector, we must know that a vector is defined as the std::vector class template i
7 min read
Templates in C++ C++ template is a powerful tool that allows you to write a generic code that can work with any data type. The idea is to simply pass the data type as a parameter so that we don't need to write the same code for different data types.For example, same sorting algorithm can work for different type, so
9 min read
Operator Overloading in C++ in C++, Operator overloading is a compile-time polymorphism. It is an idea of giving special meaning to an existing operator in C++ without changing its original meaning.In this article, we will further discuss about operator overloading in C++ with examples and see which operators we can or cannot
8 min read
C++ Classes and Objects In C++, classes and objects are the basic building block that leads to Object-Oriented programming in C++. We will learn about C++ classes, objects, look at how they work and how to implement them in our C++ program.C++ ClassesA class is a user-defined data type, which holds its own data members and
9 min read
C++ Interview Questions and Answers (2025) C++ - the must-known and all-time favourite programming language of coders. It is still relevant as it was in the mid-80s. As a general-purpose and object-oriented programming language is extensively employed mostly every time during coding. As a result, some job roles demand individuals be fluent i
15+ min read
C++ Polymorphism The word polymorphism means having many forms. A real-life example of polymorphism is a person who at the same time can have different characteristics. A man at the same time is a father, a husband, and an employee. So, the same person exhibits different behaviour in different situations. This is ca
5 min read