How to use Exponentiation by Squaring In Javascript

Exponentiation by Squaring is an efficient method for calculating large powers of a number. It reduces the number of multiplications required by breaking down the exponentiation process into smaller parts.

Example: In this example, we will calculate 2 to the power of 10 using Exponentiation by Squaring.

JavaScript
// Function to compute power using Exponentiation by Squaring
function powerBySquaring(base, exponent) {
    if (exponent === 0) return 1;
    if (exponent % 2 === 0) {
        let halfPower = powerBySquaring(base, exponent / 2);
        return halfPower * halfPower;
    } else {
        return base * powerBySquaring(base, exponent - 1);
    }
}

// Base number input
let base = 2;

// Power input
let exponent = 10;

// Calculate and display output
console.log(powerBySquaring(base, exponent));

Output
1024




JavaScript Program to Compute Power of a Number

In this article, we will demonstrate different approaches for computing the Power of a Number using JavaScript.

The Power of a Number can be computed by raising a number to a certain exponent. It can be denoted using a^b, where the ‘a’ represents the base number & the ‘b’ represents the number to which the power is to be raised. These programs will have input numbers and power and will show the resulting output. There are various techniques to calculate the power of a number, which are described below with their illustrations.

Table of Content

  • Using JavaScript Loops
  • Using Recursion
  • Using the Math.pow() Method
  • Using JavaScript Exponentiation (**) Operator
  • Using Exponentiation by Squaring

Similar Reads

Using JavaScript Loops

In this method, we will use JavaScript for loop to iterate and calculate output by multiplication....

Using Recursion

In this method, we will use a recursive function to iterate and perform multiplication at every iteration....

Using the Math.pow() Method

This is another method to method that is used to power a number i.e., the value of the number raised to some exponent. Here, we will use this method to calculate the power of the number....

Using JavaScript Exponentiation (**) Operator

This method can also be utilized to find the power of the first operator raised to the second operator, & it is denoted by a double asterisk(**) symbol....

Using Exponentiation by Squaring

Exponentiation by Squaring is an efficient method for calculating large powers of a number. It reduces the number of multiplications required by breaking down the exponentiation process into smaller parts....