Skip to content

Commit ae3bd72

Browse files
committed
Add Iterative Binary Exponentiation
1 parent 351c093 commit ae3bd72

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
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+
// Examples:
5+
// 2^3 = 8
6+
// 5^0 = 1
7+
8+
// Uses the fact that
9+
// exponent(x, n)
10+
// = exponent(x*x, floor(n/2)) ; if n is odd
11+
// = x*exponent(x*x, floor(n/2)) ; if n is even
12+
const exponent = (x, n) => {
13+
let ans = 1
14+
while(n > 0) {
15+
if(n%2 != 0) ans *= x
16+
n = Math.floor(n/2)
17+
if(n > 0) x *= x
18+
}
19+
return ans
20+
}
21+
22+
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)