The Wayback Machine - https://web.archive.org/web/20240930213203/https://www.geeksforgeeks.org/write-a-c-program-to-calculate-powxn/
Open In App

Write program to calculate pow(x, n)

Last Updated : 02 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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

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));
    }
}
Python
# 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.
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>
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
?>

Output
8

Time Complexity: O(2^y) , due to redundant calculations from multiple recursive calls.
Auxiliary Space: O(log y)

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.
Python
# 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>

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.
Python
# 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.
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>
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
?>
Rust
/*
Below funtion implements pow functionality in rust by gaurav nv
*/
fn powg(x:i32,y:i32) -> f32{
    if y == 0 {
        return 1 as f32;
    } else if y == 1{
        return x as f32;
    }

    let temp:f32 = powg(x, y/2);

    if y>0 {
        if y%2 == 0 {
            return temp * temp;
        } else {
            return temp * temp * (x as f32);
        }
    } else {
        if y%2 == 0 {
            return temp * temp;
        } else {
            return temp * temp / (x as f32);
        }        
    }
}
fn main() {
    println!("{}",powg(2, -3));
}

Output
0.125

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.
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));
    }
}
Python
# 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), for recursive call stack

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
Python
# 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)

Program to calculate pow(x,n) using Python ** operator:

To solve the problem follow the below idea:

In Python language, we can easily find power of a number using ** operator.

Below is the implementation of the above approach.

C++
#include <bits/stdc++.h>
using namespace std;

// Function to calculate power
double calculatePower(double x, int n) {
    // Calculate the power using the pow function from cmath library
    return pow(x, n);
}

// Main function
int main() {
    // Input values
    double x = 2;
    int n = 3;

    // Function call
    double result = calculatePower(x, n);

    // Output the result
    cout << result << endl;

    return 0;
}
Java
public class Main {

    // Function to calculate power
    public static double calculatePower(double x, int n) {
        // Calculate the power using the exponentiation operator (**)
        return Math.pow(x, n);
    }

    // Main function
    public static void main(String[] args) {
        // Input values
        double x = 2;
        int n = 3;

        // Function call
        double result = calculatePower(x, n);

        // Output the result
        System.out.println(result);
    }
}
Python
# Python program to illustrate use of ** operator
# to calculate power of a number
def power(x, n):

    # Calculate the power
    return x**n


# Driver Code
if __name__ == "__main__":
    x = 2
    n = 3

    # Function call
    print(power(x, n))

# This code is contributed by Susobhan Akhuli
C#
using System;

class Program
{
    // Function to calculate power
    static double CalculatePower(double x, int n)
    {
        // Calculate the power using the Math.Pow method
        return Math.Pow(x, n);
    }

    // Main function
    static void Main(string[] args)
    {
        // Input values
        double x = 2;
        int n = 3;

        // Function call
        double result = CalculatePower(x, n);

        // Output the result
        Console.WriteLine(result);
    }
}
// This code is contributed by Utkarsh
JavaScript
function GFG(x, n) {
    // Calculate the power
    return x ** n;
}
// Main function
function main() {
    // Input values
    const x = 2;
    const n = 3;
    // Function call
    const result = GFG(x, n);
    // Output the result
    console.log(result);
}
// Execute the main function
main();

Output
8

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

Program to calculate pow(x,n) using Python numpy module:

We can install NumPy by running the following command:

pip install numpy

To solve the problem follow the below idea:

In Python language, we can easily find power of a number using the NumPy library’s “power” function. This function allows you to calculate the power of a number using a single line of code.

Below is the implementation of the above approach.

C++
#include <iostream>
#include <cmath>
using namespace std;

int main() {
    int N = 2;
    int X = 3;
    int result = pow(N, X);
    cout << result << endl;
    return 0;
}
Java
import java.lang.Math;

public class Main {
    public static void main(String[] args) {
        int N = 2;
        int X = 3;
        int result = (int) Math.pow(N, X);
        System.out.println(result); // Output: 8
    }
}
//this code is contributed by Adarsh.
Python
import numpy as np

N = 2
X = 3
result = np.power(N, X)
print(result) # Output: 8

#This code is contributed by Susobhan Akhuli
JavaScript
// In this example, we're calculating N raised to the power of X
// where N = 2 and X = 3

// Calculating the result
const N = 2;
const X = 3;

// In JavaScript, the Math.pow() function is used to calculate the power of a number
// The Math.pow() function returns the base to the exponent power, that is, base^exponent
const result = Math.pow(N, X);

// Printing the result
console.log(result);
//This code is contributed by Utkarsh

Output

8

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.

C++
#include <iostream>
#include <cmath>
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;
}
Java
import java.util.*;

public class Main {
    // Function to calculate a^n using log2 and pow methods
    public static int calculatePower(int a, int n) {
        // Calculate a^n using the log2 and pow methods
        // The result is rounded to the nearest integer
        return Math.round((int) Math.pow(2, (Math.log(a) / Math.log(2)) * n));
    }

    public static void main(String[] args) {
        int a = 2;
        int n = 3;
        System.out.println(calculatePower(a, n));
    }
}
Python
import math

def calculatePower(a, n):
    return round(2 ** (math.log2(a) * n))

# Driver code
if __name__ == '__main__':
    a = 2
    n = 3
    print(calculatePower(a, n)) # Output: a^n

# This code is contributed by Susobhan Akhuli
C#
using System;

public class MainClass
{
    // Function to calculate a^n using log2 and pow methods
    public static int CalculatePower(int a, int n)
    {
        // Calculate a^n using the log2 and pow methods
        // The result is rounded to the nearest integer
        return (int)Math.Round(Math.Pow(2, (Math.Log(a) / Math.Log(2)) * n));
    }

    public static void Main(string[] args)
    {
        int a = 2;
        int n = 3;
        Console.WriteLine(CalculatePower(a, n));
    }
}
JavaScript
// Function to calculate a^n using Math.pow
function calculatePower(a, n) {
    // Calculate a^n using Math.pow
    return Math.round(Math.pow(a, n));
}

// Test the function
var a = 2;
var n = 3;
console.log(calculatePower(a, n));

Output
8

Program to calculate pow(x,n) using math.exp() function:

In math library, the math.exp() function in Python is used to calculate the value of the mathematical constant e (2.71828…) raised to a given power. It takes a single argument, which is the exponent to which the constant e should be raised, and returns the result as a float. Now, if we use combination of math.log() and math.exp() function, then we can find power of any number.

C++
#include <cmath>
#include <iostream>
using namespace std;

// Function to calculate the power of a number
int calculatePower(int x, int n)
{
    // Calculate the power using the exp and log functions
    // from the cmath library
    double result = exp(log(x) * n);

    // Round the result to the nearest integer
    result = round(result);

    return static_cast<int>(result);
}

int main()
{
    int x = 2;
    int n = 3;

    // Function call
    cout << "Result: " << calculatePower(x, n) << endl;

    return 0;
}
Java
import java.lang.Math;

public class Main {
    // Function to calculate the power of a number
    static int calculatePower(int x, int n) {
        // Calculate the power using the exp and log functions
        // from the Math library
        double result = Math.exp(Math.log(x) * n);

        // Round the result to the nearest integer
        result = Math.round(result);

        return (int) result;
    }

    public static void main(String[] args) {
        int x = 2;
        int n = 3;

        // Function call
        System.out.println("Result: " + calculatePower(x, n));
    }
}
Python
import math

def calculatePower(x, n):
      ans = math.exp(math.log(x) * n)
      ans = round(ans)
      return ans

# Driver code
if __name__ == '__main__':
    x = 2
    n = 3
    print(calculatePower(x, n)) # Output: x^n

# This code is contributed by Susobhan Akhuli
C#
using System;

class Program {
    // Function to calculate the power of a number
    static int CalculatePower(int x, int n)
    {
        // Calculate the power using the Math.Pow function
        double result = Math.Pow(x, n);

        // Round the result to the nearest integer
        result = Math.Round(result);

        return (int)result;
    }

    static void Main()
    {
        int x = 2;
        int n = 3;

        // Function call
        Console.WriteLine("Result: "
                          + CalculatePower(x, n));
    }
}
JavaScript
function GFG(x, n) {
    // Using the mathematical property to 
    // calculate the power
    const ans = Math.round(Math.exp(Math.log(x) * n));
    return ans;
}
// Driver Code
const x = 2;
const n = 3;
console.log(GFG(x, n));

Output
Result: 8

Complexity Analysis:

Time Complexity: O(1), as both math.exp() and math.log() functions run on O(1) time complexity.
Auxiliary Space: O(1), as no extra space is used.

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.



Previous Article
Next Article

Similar Reads

Write an iterative O(Log y) function for pow(x, y)
Given an integer x and a positive number y, write a function that computes xy under following conditions. a) Time complexity of the function should be O(Log y) b) Extra Space is O(1) Examples: Input: x = 3, y = 5Output: 243Input: x = 2, y = 5Output: 32 We strongly recommend that you click here and practice it, before moving on to the solution.We ha
8 min read
Calculate square of a number without using *, / and pow()
Given an integer n, calculate the square of a number without using *, / and pow(). Examples : Input: n = 5 Output: 25 Input: 7 Output: 49 Input: n = 12 Output: 144 A Simple Solution is to repeatedly add n to result. Below is the implementation of this idea. C/C++ Code // Simple solution to calculate square without // using * and pow() #include <
15 min read
Write a program to Calculate Size of a tree | Recursion
Size of a tree is the number of elements present in the tree. Size of the below tree is 5. Size() function recursively calculates the size of a tree. It works as follows:Size of a tree = Size of left subtree + 1 + Size of right subtree. Recommended PracticeSize of Binary TreeTry It!Algorithm: size(tree)1. If tree is empty then return 02. Else (a) G
14 min read
How to solve undefined reference to `pow' in C language?
When compiling a C program that uses the pow function, you might encounter the following error message: undefined reference to `pow'Why Does undefined reference to `pow' error OccursThe pow function is part of the math library in C, which is not linked by default when you compile your program. The math library (libm) contains mathematical functions
4 min read
Write a program to Delete a Tree
To delete a tree, we must traverse all the nodes of the tree and delete them one by one. So, which traversal we should use - inorder traversal, preorder traversal, or the postorder traversal? The answer is simple. We should use the postorder traversal because before deleting the parent node, we should delete its child nodes first.We can delete the
11 min read
Write a program to add two numbers in base 14
Asked by Anshya. Base 14: Decimal numbersBase 14 numbers0011223344556677889910A11B12C13D14D1 Below are the different ways to add base 14 numbers.Method 1 Thanks to Raj for suggesting this method. 1. Convert both i/p base 14 numbers to base 10. 2. Add numbers. 3. Convert the result back to base 14. Method 2 Just add the numbers in base 14 in the sam
15 min read
Write a program to reverse digits of a number
Write a program to reverse the digits of an integer. Examples : Input : num = 12345 Output: 54321 Input : num = 876 Output: 678Flowchart: ITERATIVE WAY Algorithm: Input: num (1) Initialize rev_num = 0 (2) Loop while num > 0 (a) Multiply rev_num by 10 and add remainder of num divide by 10 to rev_num rev_num = rev_num*10 + num%10; (b) Divide num b
15+ min read
Javascript Program To Write Your Own atoi()
The atoi() function in C takes a string (which represents an integer) as an argument and returns its value of type int. So basically the function is used to convert a string argument to an integer. Syntax: int atoi(const char strn) Parameters: The function accepts one parameter strn which refers to the string argument that is needed to be converted
5 min read
Write an Efficient C Program to Reverse Bits of a Number
Given an unsigned integer, reverse all bits of it and return the number with reversed bits. Input : n = 1Output : 2147483648 Explanation : On a machine with size of unsigned bit as 32. Reverse of 0....001 is 100....0. Input : n = 2147483648Output : 1 Recommended PracticeReverse BitsTry It!Method1 - Simple: Loop through all the bits of an integer. I
6 min read
Program to calculate the number of odd days in given number of years
Given an integer N, the task is to find the number of odd days in the years from 1 to N. Odd Days: Number of odd days refer to those days that are left in a certain year(s) when it's days gets converted into weeks. Say, an ordinary year has 365 days, that is 52 weeks and one odd day. This means, out of the 365 days in an ordinary year, 364 days wil
7 min read
Program to Calculate Body Mass Index (BMI)
The Body Mass Index (BMI) or Quetelet index is a value derived from the mass (weight) and height of an individual, male or female. The BMI is defined as the body mass divided by the square of the body height and is universally expressed in units of kg/m2, resulting from the mass in kilograms and height in meters. The formula is: BMI = (mass or weig
4 min read
Program to calculate age
Given the current date and birth date, find the present age. Examples: Input : Birth date = 07/09/1996 Present date = 07/12/2017 Output : Present Age = Years: 21 Months: 3 Days: 0 t Age = Years: 7 Months: 11 Days: 21 While calculating the difference in two dates we need to just keep track of two conditions that will do. If the current date is less
9 min read
Program to calculate area and perimeter of Trapezium
A trapezium is a quadrilateral with at least one pair of parallel sides, other two sides may not be parallel. The parallel sides are called the bases of the trapezium and the other two sides are called it's legs. The perpendicular distance between parallel sides is called height of trapezium. Formula : Area of Trapezium : 0.5 * (a + b) * h Perimete
5 min read
Program to calculate area and volume of a Tetrahedron
A Tetrahedron is simply a pyramid with a triangular base. It is a solid object with four triangular faces, three on the sides or lateral faces, one on the bottom or the base and four vertices or corners. If the faces are all congruent equilateral triangles, then the tetrahedron is called regular. The area of Tetrahedron can be found by using the fo
5 min read
Program to calculate area and perimeter of equilateral triangle
An equilateral triangle is a triangle in which all three sides and angles are equal. All three internal angles of equilateral triangle measures 60 degree. If we know the length of each sides of equilateral triangle, then we can use below mentioned formula to calculate area of equilateral triangle.Area of Equilateral Triangle = (sqrt(3)/4) * a * a I
4 min read
Program to calculate Area Of Octagon
A regular octagon is a closed figure with sides of the same length and internal angles of the same size. It has eight lines of reflective symmetry and rotational symmetry of order 8. The internal angle at each vertex of a regular octagon is 135°. The central angle is 45°.Properties : Convex polygon, Equilateral polygon, Isogonal figure, Isotoxal fi
3 min read
Program to calculate GST from original and net prices
Given Original cost and Net price then calculate the percentage of GSTExamples: Input : Netprice = 120, original_cost = 100 Output : GST = 20% Input : Netprice = 105, original_cost = 100 Output : GST = 5% How to calculate GST GST ( Goods and Services Tax ) which is included in netprice of product for get GST % first need to calculate GST Amount by
3 min read
Program to calculate area of Circumcircle of an Equilateral Triangle
Given the length of sides of an equilateral triangle. We need to write a program to find the area of Circumcircle of the given equilateral triangle.Examples: Input : side = 6 Output : Area of circumscribed circle is: 37.69 Input : side = 9 Output : Area of circumscribed circle is: 84.82 All three sides of equilateral triangle are of equal length an
4 min read
Program to calculate Percentile of a student based on rank
Given the rank of a student and the total number of students appearing in an examination, the task is to find the percentile of the student. The percentile of a student is the % of the number of students having marks less than him/her. Examples: Input: Rank: 805, Total Number of Students Appeared: 97481 Output: 99.17 Explanation: ((97481 - 805) / 9
3 min read
Program to calculate the Surface Area of a Triangular Prism
In mathematics, a triangular prism is a three-dimensional solid shape with two identical ends connected by equal parallel lines, and have 5 faces, 9 edges, and 6 vertices. where "b" is the length of the base, "h" is the height of the triangle, "s1, s2, s3" are the respective length of each side of the triangle, and H is the height of the prism (whi
5 min read
Program to calculate area of an Circle inscribed in a Square
Given the side of a square. The task is to find the area of an inscribed circle in a square.Examples: Input : a = 8 Output : Area of an inscribed circle: 50.24 Input : a = 12.04 Output : Area of an inscribed circle: 113.795 Given a square i.e. all sides of a square are of equal length and all four angles are 90 degrees. Below diagram depicts an ins
4 min read
Program to calculate distance between two points in 3 D
Given two coordinates (x1, y1, z1) and (x2, y2, z2) in 3 dimension. The task is to find the distance between them.Examples : Input: x1, y1, z1 = (2, -5, 7) x2, y2, z1 = (3, 4, 5) Output: 9.2736184955 Input: x1, y1, z1 = (0, 0, 0) x2, y2, z1 = (1, 1, 1) Output: 1.73205080757 Approach: The formula for distance between two points in 3 dimension i.e (x
5 min read
Program to calculate Profit Or Loss
Given the Cost Price(CP) and Selling Price(SP) of a product. The task is to Calculate the Profit or Loss.Examples: Input: CP = 1500, SP = 2000 Output: 500 Profit Input: CP = 3125, SP = 1125 Output: 2000 Loss Formula: Profit = (Selling Price - Cost Price) Loss = (Cost Price - Selling Price) Below is the required implementation: C/C++ Code // C++ cod
4 min read
Program to calculate the profit sharing ratio
Given an array of amounts and time_period that represents the amount of money N persons invest and the time period for which they had invested. The task is to calculate the Profit ratio at the End.Examples: Input: n = 2, Amount1 = 7000, Time1 = 12 months Amount2 = 6000, Time2 = 6 months Output: 7 : 3Input: n = 3, Amount1 = 5000, Time1 = 6 months Am
7 min read
Program to calculate Bitonicity of an Array
Given an array of [Tex]N [/Tex]integers. The task is to find the Bitonicity of the given array.The Bitonicity of an array arr[] can be defined as: B[i] = 0, if i = 0. = B[i-1] + 1, if arr[i] > arr[i-1] = B[i-1] - 1, if arr[i] < arr[i-1] = B[i-1], if arr[i] = arr[i-1] Bitonicity will be last element of array B[]. Examples: Input : arr[] = {1,
5 min read
Program to calculate Root Mean Square
Given an array of N numbers. The task is to calculate the Root Mean Square(RMS) of the given numbers. Examples: Input: arr[] = {1, 2, 3, 4, 5} Output: 3.31662 Input: arr[] = {10, 4, 6, 8} Output: 7.34847 Approach: The Root Mean Square value of N numbers x1,x2,x3,.....xn can be given as, RMS method first calculates the square of each number and then
4 min read
Program to Calculate the Edge Cover of a Graph
Given the number of vertices N of a graph. The task is to determine the Edge cover.Edge Cover: Minimum number of edges required to cover all vertex is known as Edge Cover. Examples: Input : N = 5 Output : 3 Input : N = 4 Output : 2 Example 1: For N = 5 vertices, Edge Cover is: 3 (Choosing the edges marked in Red, all of the vertices will get covere
3 min read
Program to Calculate the Perimeter of a Decagon
Given side [Tex]S [/Tex]of a Decagon, the task is to find out the Perimeter of the Decagon.Explanation : In geometry, a decagon is a ten-sided polygon or 10-gon. A regular decagon has all sides of equal length and each internal angle will always be equal to 144 degrees. Examples: Input : S = 5 Output : The Perimeter of Decagon is : 50 Input : S = 8
3 min read
Program to calculate area and perimeter of a rhombus whose diagonals are given
Given the length of diagonals of a rhombus, d1 and d2. The task is to find the perimeter and the area of that rhombus. A rhombus is a polygon having 4 equal sides in which both the opposite sides are parallel, and opposite angles are equal. Examples: Input: d1 = 2 and d2 = 4 Output: The area of rhombus with diagonals 2 and 4 is 4. The perimeter of
5 min read
Program to calculate the Area and Perimeter of Incircle of an Equilateral Triangle
Given the length of sides of an equilateral triangle, the task is to find the area and perimeter of Incircle of the given equilateral triangle. Examples: Input: side = 6 Output: Area = 9.4. Perimeter = 10.88 Input: side = 9 Output: Area = 21.21, Perimeter = 16.32 Properties of an Incircle are: The center of the Incircle is same as the center of the
4 min read