How to use Memoization with Recursion In Javascript
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)}`); |
The recursively calculated value of 3^4 is: 81
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.
Table of Content
- Using Recursion
- Using Memoization with Recursion