mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-04 15:39:42 +08:00
Add Iterative Binary Exponentiation
This commit is contained in:
22
Maths/BinaryExponentiationIterative.js
Normal file
22
Maths/BinaryExponentiationIterative.js
Normal file
@ -0,0 +1,22 @@
|
||||
// To calculate x^n i.e. exponent(x, n) in O(log n) time in iterative way
|
||||
// n is an integer and n >= 0
|
||||
|
||||
// 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
Maths/test/BinaryExponentiationIterative.test.js
Normal file
15
Maths/test/BinaryExponentiationIterative.test.js
Normal file
@ -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)
|
||||
})
|
||||
})
|
Reference in New Issue
Block a user