mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-05 16:26:47 +08:00
chore: Add PowLogarithmic in Math (#836)
* Add PowLogarithmic in Math * add description
This commit is contained in:
26
Maths/PowLogarithmic.js
Normal file
26
Maths/PowLogarithmic.js
Normal file
@ -0,0 +1,26 @@
|
||||
import { isEven } from './IsEven'
|
||||
|
||||
/**
|
||||
* This algorithm is divide the n by 2 every time and pass this to recursive call to find the result of smaller result.
|
||||
* why? Because
|
||||
* x^n => [if n is even] x^(n / 2) * x^(n / 2) (example : 7^4 => 7^2 * 7^2)
|
||||
* [if n is odd] x^(n / 2) * x^(n / 2) * x (example : 7^5 => 7^2 * 7^2 * 7)
|
||||
* and repeat the above step until we reach to the base case.
|
||||
*
|
||||
* @function PowLogarithmic
|
||||
* @description Given two integers x and n, return x^n in logarithmic complexity.
|
||||
* @param {Integer} x - The input integer
|
||||
* @param {Integer} n - The input integer
|
||||
* @return {Integer} - Returns x^n.
|
||||
* @see [Pow-Logarithmic](https://www.geeksforgeeks.org/write-a-c-program-to-calculate-powxn/)
|
||||
*/
|
||||
const powLogarithmic = (x, n) => {
|
||||
if (n === 0) return 1
|
||||
const result = powLogarithmic(x, Math.floor(n / 2))
|
||||
if (isEven(n)) {
|
||||
return result * result
|
||||
}
|
||||
return result * result * x
|
||||
}
|
||||
|
||||
export { powLogarithmic }
|
15
Maths/test/PowLogarithmic.test.js
Normal file
15
Maths/test/PowLogarithmic.test.js
Normal file
@ -0,0 +1,15 @@
|
||||
import { powLogarithmic } from '../PowLogarithmic'
|
||||
|
||||
describe('PowLogarithmic', () => {
|
||||
it('should return 1 for numbers with exponent 0', () => {
|
||||
expect(powLogarithmic(2, 0)).toBe(1)
|
||||
})
|
||||
|
||||
it('should return 0 for numbers with base 0', () => {
|
||||
expect(powLogarithmic(0, 23)).toBe(0)
|
||||
})
|
||||
|
||||
it('should return the base to the exponent power', () => {
|
||||
expect(powLogarithmic(24, 4)).toBe(331776)
|
||||
})
|
||||
})
|
Reference in New Issue
Block a user