Skip to content

Add Iterative Binary Exponentiation #530

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Oct 30, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions Maths/BinaryExponentiationIterative.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// To calculate x^n i.e. exponent(x, n) in O(log n) time in iterative way
// n is an integer and n >= 0

// Explanation: https://en.wikipedia.org/wiki/Exponentiation_by_squaring

// Examples:
// 2^3 = 8
// 5^0 = 1

// Uses the fact that
// exponent(x, n)
// = exponent(x*x, floor(n/2)) ; if n is odd
// = x*exponent(x*x, floor(n/2)) ; if n is even
const exponent = (x, n) => {
let ans = 1
while (n > 0) {
if (n % 2 !== 0) ans *= x
n = Math.floor(n / 2)
if (n > 0) x *= x
}
return ans
}

export { exponent }
15 changes: 15 additions & 0 deletions Maths/test/BinaryExponentiationIterative.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { exponent } from '../BinaryExponentiationIterative'

describe('exponent', () => {
it('should return 1 when power is 0', () => {
expect(exponent(5, 0)).toBe(1)
})

it('should return 0 when base is 0', () => {
expect(exponent(0, 7)).toBe(0)
})

it('should return the value of a base raised to a power', () => {
expect(exponent(3, 5)).toBe(243)
})
})