Horje
JavaScript Program to Calculate Power Using Recursion

A program to calculate power using recursion involves defining a function that recursively multiplies a base number by itself, decrementing the exponent until it reaches 0. The below-listed examples can be utilized to calculate powers using recursion in JavaScript.

Using Recursion

Basic recursion involves defining a function that calls itself with modified parameters until reaching a base case, where a specific condition is met. This approach simplifies solving complex problems by breaking them down into smaller, self-repeating tasks.

Example: The below code recursively calculates the power of the passed base number in JavaScript.

Javascript

function myPowerFunction(base, exponent) {
    if (exponent === 0) {
        return 1;
    }
    const result =
        base * myPowerFunction(base, exponent - 1);
    return result;
}
const b = 2;
const e = 4;
console.log
    (`The recursively calculated value of ${b}^${e} is: ${myPowerFunction(b, e)}`);

Output

The recursively calculated value of 2^4 is: 16

Using Memoization with Recursion

Memoization optimizes recursive functions by caching computed results. Before computing, the function checks if the result for given inputs exists in the cache it returns the cached result. Otherwise, it computes the power, stores, and returns it. This reduces redundant computations, enhancing performance.

Example: The below code will use memoization technique with recursion to improve the performance.

Javascript

const memo = {};
 
function myPowerFunction(base, exponent) {
    const key = base + ',' + exponent;
    if (key in memo) {
        return memo[key];
    }
    if (exponent === 0) {
        return 1;
    }
    const result =
        base * myPowerFunction(base, exponent - 1);
    memo[key] = result;
    return result;
}
 
const b = 3;
const e = 4;
console.log
    (`The recursively calculated value of ${b}^${e} is: ${myPowerFunction(b, e)}`);

Output

The recursively calculated value of 3^4 is: 81



Reffered: https://www.geeksforgeeks.org


JavaScript

Related
Replace all Occurrences of a Substring in a String in JavaScript Replace all Occurrences of a Substring in a String in JavaScript
How to Declare Variables in TypeScript ? How to Declare Variables in TypeScript ?
Explain the Concept of Interfaces in TypeScript ? Explain the Concept of Interfaces in TypeScript ?
What is the use of Union Type in TypeScript ? What is the use of Union Type in TypeScript ?
How to implement Type narrowing in TypeScript? How to implement Type narrowing in TypeScript?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
12