Skip to content
Related Articles

Related Articles

Write program to calculate pow(x, n)

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 08 Nov, 2022
Improve Article
Save Article

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.

program to calculate pow(x,n)

Examples : 

Input : x = 2, n = 3
Output : 8

Input : x = 7, n = 2
Output : 49

Recommended Practice

Naive Approach: To solve the problem follow the below idea:

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;
}

Java




// Java program for the above approach
 
import java.io.*;
 
class Gfg {
 
    // Naive iterative solution to calculate pow(x, n)
    public static long power(int x, int n)
    {
        // Initialize result by 1
        long pow = 1L;
 
        // Multiply x for n times
        for (int i = 0; i < n; i++) {
            pow = pow * x;
        }
 
        return pow;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int x = 2;
        int n = 3;
        System.out.println(power(x, n));
    }
};

Python




# Python3 program for the above approach
def power(x, n):
 
    # initialize result by 1
    pow = 1
 
    # Multiply x for n times
    for i in range(n):
        pow = pow * x
 
    return pow
 
 
# Driver code
if __name__ == '__main__':
 
    x = 2
    n = 3
 
       # Function call
    print(power(x, n))

C#




// C# program for the above approach
using System;
 
public class Gfg {
 
    // Naive iterative solution to calculate pow(x, n)
    static long power(int x, int n)
    {
        // Initialize result by 1
        long pow = 1L;
 
        // Multiply x for n times
        for (int i = 0; i < n; i++) {
            pow = pow * x;
        }
 
        return pow;
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        int x = 2;
        int n = 3;
        Console.WriteLine(power(x, n));
    }
};
 
// This code contributed by Pushpesh Raj

Javascript




// Naive iterative solution to calculate pow(x, n)
function power( x, n)
{
    // Initialize result to 1
    let pow = 1;
 
    // Multiply x for n times
    for (let i = 0; i < n; i++) {
        pow = pow * x;
    }
 
    return pow;
}
 
// Driver code
 
    let x = 2;
    let n = 3;
 
    // Function call
    let result = power(x, n);
    console.log( result );
 
// This code is contributed by garg28harsh.

Output

8

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)

C




// C program for the above approach
#include <stdio.h>
 
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
    printf("%d\n", power(x, n));
}
 
// This code is contributed by Aditya Kumar (adityakumar129)

Java




// Java program for the above approach
import java.io.*;
 
class GFG {
    public static 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
    public static void main(String[] args)
    {
        int x = 2;
        int n = 3;
 
        // Function call
        System.out.println(power(x, n));
    }
}

Python3




# Python3 program for the above approach
def power(x, 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
if __name__ == "__main__":
    x = 2
    n = 3
 
    # Function call
    print(power(x, n))
 
# This code is contributed by shivani.

C#




// C# program for the above approach
using System;
 
class GFG {
 
    public static 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
    public static void Main(String[] args)
    {
        int x = 2;
        int n = 3;
 
        // Function call
        Console.WriteLine(power(x, n));
    }
}
 
// This code is contributed by Rajput-Ji

Javascript




<script>
 
// javascript program for the above approach
    function power(x , n) {
 
        // If x^0 return 1
        if (n == 0)
            return 1;
 
        if (x == 0)
            return 0;
 
        // For all other cases
        return x * power(x, n - 1);
    }
 
    // Driver Code
     
        var x = 2;
        var n = 3;
 
        document.write(power(x, n));
 
// This code is contributed by Rajput-Ji
 
</script>

Output

8

Time Complexity: O(n)
Auxiliary Space: O(n) n is the size of the recursion stack

Program to calculate pow(x, n) using Divide and Conqueror approach:

To solve the problem follow the below idea:

The problem can be recursively defined by:

  • power(x, n) = power(x, n / 2) * power(x, n / 2);        // if n is even
  • power(x, n) = x * power(x, n / 2) * power(x, n / 2);    // if n is odd

Below is the implementation of the above approach:

C++




// C++ program to calculate pow(x,n)
#include <bits/stdc++.h>
using namespace std;
class gfg {
 
    /* Function to calculate x raised to the power y */
public:
    int power(int x, unsigned int y)
    {
        if (y == 0)
            return 1;
        else if (y % 2 == 0)
            return power(x, y / 2) * power(x, y / 2);
        else
            return x * power(x, y / 2) * power(x, y / 2);
    }
};
 
/* Driver code */
int main()
{
    gfg g;
    int x = 2;
    unsigned int y = 3;
 
    // Function call
    cout << g.power(x, y);
    return 0;
}
 
// This code is contributed by SoM15242

C




// C program to calculate pow(x,n)
#include <stdio.h>
 
/* Function to calculate x raised to the power y */
int power(int x, unsigned int y)
{
    if (y == 0)
        return 1;
    else if (y % 2 == 0)
        return power(x, y / 2) * power(x, y / 2);
    else
        return x * power(x, y / 2) * power(x, y / 2);
}
 
/* Driver code */
int main()
{
    int x = 2;
    unsigned int y = 3;
 
    // Function call
    printf("%d", power(x, y));
    return 0;
}

Java




// Java program to calculate pow(x,n)
 
class GFG {
    /* Function to calculate x raised to the power y */
    static int power(int x, int y)
    {
        if (y == 0)
            return 1;
        else if (y % 2 == 0)
            return power(x, y / 2) * power(x, y / 2);
        else
            return x * power(x, y / 2) * power(x, y / 2);
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int x = 2;
        int y = 3;
 
        // Function call
        System.out.printf("%d", power(x, y));
    }
}
 
// This code is contributed by Smitha Dinesh Semwal

Python




# Python3 program to calculate pow(x,n)
 
# Function to calculate x
# raised to the power y
 
 
def power(x, y):
 
    if (y == 0):
        return 1
    elif (int(y % 2) == 0):
        return (power(x, int(y / 2)) *
                power(x, int(y / 2)))
    else:
        return (x * power(x, int(y / 2)) *
                power(x, int(y / 2)))
 
 
# Driver Code
if __name__ == "__main__":
    x = 2
    y = 3
 
    # Function call
    print(power(x, y))
 
# This code is contributed by Smitha Dinesh Semwal.

C#




// C# program to calculate pow(x,n)
 
using System;
 
public class GFG {
 
    // Function to calculate x raised to the power y
    static int power(int x, int y)
    {
        if (y == 0)
            return 1;
        else if (y % 2 == 0)
            return power(x, y / 2) * power(x, y / 2);
        else
            return x * power(x, y / 2) * power(x, y / 2);
    }
 
    // Driver code
    public static void Main()
    {
        int x = 2;
        int y = 3;
 
        // Function call
        Console.Write(power(x, y));
    }
}
 
// This code is contributed by shiv_bhakt.

PHP




<?php
// php program to calculate pow(x,n)
function power($x, $y)
{
    if ($y == 0)
        return 1;
    else if ($y % 2 == 0)
        return power($x, (int)$y / 2) *
            power($x, (int)$y / 2);
    else
        return $x * power($x, (int)$y / 2) *
                    power($x, (int)$y / 2);
}
 
// Driver Code
$x = 2;
$y = 3;
 
// Function call
echo power($x, $y);
     
// This code is contributed by ajit
?>

Javascript




<script>
// Javascript program to calculate pow(x,n)
 
// Function to calculate x
// raised to the power y
function power(x, y)
{
    if (y == 0)
        return 1;
    else if (y % 2 == 0)
        return power(x, parseInt(y / 2, 10)) *
            power(x, parseInt(y / 2, 10));
    else
        return x * power(x, parseInt(y / 2, 10)) *
                power(x, parseInt(y / 2, 10));
}
 
// Driver code
let x = 2;
let y = 3;
 
document.write(power(x, y));
 
// This code is contributed by mukesh07
 
</script>

Output

8

Time Complexity: O(n)
Auxiliary Space: O(n)

An Optimized Divide and Conquer Solution:

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++




/* 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;
}
 
// This code is contributed by Shubhamsingh10

C




/* 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;
}

Java




/* Function to calculate x raised to the power y in
 * O(logn)*/
static int power(int x, 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;
}
 
// This code is contributed by divyeshrabadiya07.

Python3




# Function to calculate x raised to the power y in O(logn)
def power(x, y):
    temp = 0
    if(y == 0):
        return 1
    temp = power(x, int(y / 2))
    if (y % 2 == 0)
    return temp * temp
    else
    return x * temp * temp
 
# This code is contributed by avanitrachhadiya2155

C#




/* Function to calculate x raised to the power y in
 * O(logn)*/
static int power(int x, 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;
}
 
// This code is contributed by divyesh072019.

Javascript




<script>
 
/* Function to calculate x raised to the power y in O(logn)*/
function power(x , y)
{
    var temp;
    if( y == 0)
        return 1;
    temp = power(x, y / 2);
    if (y % 2 == 0)
        return temp*temp;
    else
        return x*temp*temp;
}
 
// This code is contributed by todaysgaurav
 
</script>

Output

8

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

C




/* Extended version of power function that can work
 for float x and negative y*/
#include <stdio.h>
 
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
    printf("%f", power(x, y));
    return 0;
}

Java




/* Java code for extended version of power function
that can work for float x and negative y */
class GFG {
 
    static 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 */
    public static void main(String[] args)
    {
        float x = 2;
        int y = -3;
 
        // Function call
        System.out.printf("%f", power(x, y));
    }
}
 
// This code is contributed by  Smitha Dinesh Semwal.

Python3




# Python3 code for extended version
# of power function that can work
# for float x and negative y
 
 
def power(x, y):
 
    if(y == 0):
        return 1
    temp = power(x, int(y / 2))
 
    if (y % 2 == 0):
        return temp * temp
    else:
        if(y > 0):
            return x * temp * temp
        else:
            return (temp * temp) / x
 
 
# Driver Code
if __name__ == "__main__":
    x, y = 2, -3
 
    # Function call
    print('%.6f' % (power(x, y)))
 
# This code is contributed by Smitha Dinesh Semwal.

C#




// C# code for extended version of power function
// that can work for float x and negative y
 
using System;
 
public class GFG {
 
    static 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
    public static void Main()
    {
        float x = 2;
        int y = -3;
 
        // Function call
        Console.Write(power(x, y));
    }
}
 
// This code is contributed by shiv_bhakt.

PHP




<?php
// Extended version of power
// function that can work
// for float x and negative y
 
function power($x, $y)
{
    $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
$x = 2;
$y = -3;
 
// Function call
echo power($x, $y);
 
// This code is contributed by ajit
?>

Javascript




<script>
 
// Javascript code for extended
// version of power function that
// can work for var x and negative y
function power(x, y)
{
    var temp;
     
    if (y == 0)
        return 1;
         
    temp = power(x, parseInt(y / 2));
 
    if (y % 2 == 0)
        return temp * temp;
    else
    {
        if (y > 0)
            return x * temp * temp;
        else
            return (temp * temp) / x;
    }
}
 
// Driver code
var x = 2;
var y = -3;
 
document.write( power(x, y).toFixed(6));
 
// This code is contributed by aashish1995
 
</script>

Output

0.125

Time Complexity: O(log |n|)
Auxiliary Space: O(1)

 

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.

Java




// Java program for the above approach
import java.io.*;
 
class GFG {
    public static int power(int x, int n)
    {
 
        // Math.pow() is a function that
        // return floating number
        return (int)Math.pow(x, n);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int x = 2;
        int n = 3;
 
        // Function call
        System.out.println(power(x, n));
    }
}

Python3




# Python3 program for the above approach
def power(x, n):
 
    # Return type of pow()
    # function is double
    return pow(x, n)
 
 
# Driver Code
if __name__ == "__main__":
    x = 2
    n = 3
 
    # Function call
    print(power(x, n))
 
# This code is contributed by susmitakundugoaldanga

C#




// C# program for the above approach
 
using System;
 
public class GFG {
 
    public static int power(int x, int n)
    {
 
        // Math.pow() is a function that
        // return floating number
        return (int)Math.Pow(x, n);
    }
 
    // Driver code
    static public void Main()
    {
        int x = 2;
        int n = 3;
 
        // Function call
        Console.WriteLine(power(x, n));
    }
}

Javascript




<script>
 
// Javascript program for the above approach
 
    function power( x, n)
    {
         
        // Math.pow() is a function that
        // return floating number
        return parseInt(Math.pow(x, n));
    }
 
    // Driver Code
     
        let x = 2;
        let n = 3;
 
        document.write(power(x, n));
         
// This code is contributed by sravan kumar
 
</script>

Output

8

Time Complexity: O(log n)
Auxiliary Space: O(1)

Program to calculate pow(x,n) using Binary operators:

To solve the problem follow the below idea:

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

Java




// Java program for above approach
 
import java.io.*;
 
class GFG {
 
    static int power(int x, int n)
    {
        int result = 1;
        while (n > 0) {
            if (n % 2 != 0) // y is odd
            {
                result = result * x;
            }
            x = x * x;
            n = n >> 1; // y=y/2;
        }
        return result;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int x = 2;
        int n = 3;
 
        // Function call
        System.out.println(power(x, n));
    }
}
 
// This code is contributed by Suruchi Kumari

Python3




# Python3 program for the above approach
def power(x, n):
 
    result = 1
    while (n > 0):
        if (n % 2 == 0):
            # y is even
 
            x = x * x
            n = n / 2
 
        else:
            # y isn't even
 
            result = result * x
            n = n - 1
 
    return result
 
 
# Driver Code
if __name__ == "__main__":
    x = 2
    n = 3
 
    # Function call
    print((power(x, n)))
 
# This code is contributed by shivanisinghss2110

C#




// C# program for above approach
using System;
 
class GFG {
 
    static int power(int x, int n)
    {
        int result = 1;
 
        while (n > 0) {
 
            // y is even
            if (n % 2 == 0) {
                x = x * x;
                n = n / 2;
            }
 
            // y isn't even
            else {
                result = result * x;
                n = n - 1;
            }
        }
        return result;
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        int x = 2;
        int y = 3;
 
        // Function call
        Console.Write(power(x, y));
    }
}
 
// This code is contributed by shivanisinghss2110

Javascript




<script>
// Javascript program for the above approach
 
function power(x,y)
{
    let result = 1;
    while (y > 0) {
        if (y % 2 == 0) // y is even
        {
            x = x * x;
            y = Math.floor(y / 2);
        }
        else // y isn't even
        {
            result = result * x;
            y = y - 1;
        }
    }
    return result;
}
 
// Driver Code
let x = 2;
let y = 3;
document.write(power(x, y))
 
// This code is contributed by rag2127
</script>

Output

8

Time Complexity: O(log n)
Auxiliary Space: O(1)

Related Articles:
Write an iterative O(Log y) function for pow(x, y) 
Modular Exponentiation (Power in Modular Arithmetic)

If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!