

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Implementing Math function and return m^n in JavaScript
We are required to write a JavaScript function that takes in two numbers say m and n. Then function should calculate and return m^n.
For example − For m = 4, n = 3, then
power(4, 3) = 4^3 = 4 * 4 * 4 = 64 power(6, 3) = 216
The code for this will be the following using the power() function in JavaScript −
Example
const power = (m, n) => { if(n < 0 && m !== 0){ return power(1/m, n*-1); }; if(n === 0){ return 1; } if(n === 1){ return m; }; if (n % 2 === 0){ const res = power(m, n / 2); return res * res; }else{ return power(m, n - 1) * m; }; }; console.log(power(4, 3)); console.log(power(6, 3));
Output
And the output in the console will be −
64 216
- Related Questions & Answers
- Take two numbers m and n & return two numbers whose sum is n and product m in JavaScript
- Math. fround() function in JavaScript
- Math. hypot() function in JavaScript
- Implementing the Array.prototype.lastIndexOf() function in JavaScript
- Sum of even numbers from n to m regardless if n<m or n>m JavaScript
- Implementing custom function like String.prototype.split() function in JavaScript
- Implementing a custom function like Array.prototype.filter() function in JavaScript
- Get minimum number without a Math function JavaScript
- Construct DPDA for anbmc(n+m) n,m≥1 in TOC
- Construct PDA for L = {0n1m2(n+m) | m,n >=1}
- Calculate the value of (m)1/n in JavaScript
- Find a positive number M such that gcd(N^M,N&M) is maximum in Python
- Construct Pushdown automata for L = {0n1m2(n+m) | m,n = 0} in C++
- Construct DPDA for a(n+m)bmcn n,m≥1 in TOC
- Count of numbers satisfying m + sum(m) + sum(sum(m)) = N in C++
Advertisements