Skip to content

Commit 410ecd2

Browse files
authored
Merge pull request TheAlgorithms#530 from rahul1995/binary-expo
Add Iterative Binary Exponentiation
2 parents 351c093 + 5e6d813 commit 410ecd2

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// To calculate x^n i.e. exponent(x, n) in O(log n) time in iterative way
2+
// n is an integer and n >= 0
3+
4+
// Explanation: https://en.wikipedia.org/wiki/Exponentiation_by_squaring
5+
6+
// Examples:
7+
// 2^3 = 8
8+
// 5^0 = 1
9+
10+
// Uses the fact that
11+
// exponent(x, n)
12+
// = exponent(x*x, floor(n/2)) ; if n is odd
13+
// = x*exponent(x*x, floor(n/2)) ; if n is even
14+
const exponent = (x, n) => {
15+
let ans = 1
16+
while (n > 0) {
17+
if (n % 2 !== 0) ans *= x
18+
n = Math.floor(n / 2)
19+
if (n > 0) x *= x
20+
}
21+
return ans
22+
}
23+
24+
export { exponent }
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import { exponent } from '../BinaryExponentiationIterative'
2+
3+
describe('exponent', () => {
4+
it('should return 1 when power is 0', () => {
5+
expect(exponent(5, 0)).toBe(1)
6+
})
7+
8+
it('should return 0 when base is 0', () => {
9+
expect(exponent(0, 7)).toBe(0)
10+
})
11+
12+
it('should return the value of a base raised to a power', () => {
13+
expect(exponent(3, 5)).toBe(243)
14+
})
15+
})

0 commit comments

Comments
 (0)