Skip to content

Commit c1c895b

Browse files
chore: Add PowLogarithmic in Math (TheAlgorithms#836)
* Add PowLogarithmic in Math * add description
1 parent 65931be commit c1c895b

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

Maths/PowLogarithmic.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import { isEven } from './IsEven'
2+
3+
/**
4+
* This algorithm is divide the n by 2 every time and pass this to recursive call to find the result of smaller result.
5+
* why? Because
6+
* x^n => [if n is even] x^(n / 2) * x^(n / 2) (example : 7^4 => 7^2 * 7^2)
7+
* [if n is odd] x^(n / 2) * x^(n / 2) * x (example : 7^5 => 7^2 * 7^2 * 7)
8+
* and repeat the above step until we reach to the base case.
9+
*
10+
* @function PowLogarithmic
11+
* @description Given two integers x and n, return x^n in logarithmic complexity.
12+
* @param {Integer} x - The input integer
13+
* @param {Integer} n - The input integer
14+
* @return {Integer} - Returns x^n.
15+
* @see [Pow-Logarithmic](https://www.geeksforgeeks.org/write-a-c-program-to-calculate-powxn/)
16+
*/
17+
const powLogarithmic = (x, n) => {
18+
if (n === 0) return 1
19+
const result = powLogarithmic(x, Math.floor(n / 2))
20+
if (isEven(n)) {
21+
return result * result
22+
}
23+
return result * result * x
24+
}
25+
26+
export { powLogarithmic }

Maths/test/PowLogarithmic.test.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import { powLogarithmic } from '../PowLogarithmic'
2+
3+
describe('PowLogarithmic', () => {
4+
it('should return 1 for numbers with exponent 0', () => {
5+
expect(powLogarithmic(2, 0)).toBe(1)
6+
})
7+
8+
it('should return 0 for numbers with base 0', () => {
9+
expect(powLogarithmic(0, 23)).toBe(0)
10+
})
11+
12+
it('should return the base to the exponent power', () => {
13+
expect(powLogarithmic(24, 4)).toBe(331776)
14+
})
15+
})

0 commit comments

Comments
 (0)