Skip to content
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

feat: added binary exponentation interative function #271

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
40 changes: 40 additions & 0 deletions maths/binary_exponentiation_iterative.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/**
* @function binaryExponentiationIterative
* @description Calculate the result of a number raised to the power of another number using binary exponentiation.
* @param {number} base - The base number.
* @param {number} exponent - The exponent number.
* @returns {number} - The result of the base number raised to the power of the exponent number.
* @throws {TypeError} - when base is not a number.
* @throws {TypeError} - when exponent is not a positive integer.
* @example binaryExponentiationIterative(2, 10) => 1024
*/

export const binaryExponentiationIterative = (
base: number,
exponent: number
): number => {
if (typeof base !== 'number') {
throw new TypeError('base must be a number')
}

if (!Number.isInteger(exponent) || exponent < 0) {
throw new TypeError('exponent must be a positive integer')
}

if (exponent === 0) return 1
if (exponent === 1) return base
if (base === 0) return 0
if (base === 1) return 1

let result = 1

while (exponent > 0) {
if (exponent % 2 === 1) {
result *= base
}
base *= base
exponent = Math.floor(exponent / 2)
}

return result;
}
21 changes: 21 additions & 0 deletions maths/test/binary_exponentation_interative.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { binaryExponentiationIterative } from '../binary_exponentiation_iterative'

describe('binaryExponentiationIterative', () => {
test('should throw a TypeError when base is not a number', () => {
expect(() =>
binaryExponentiationIterative('2' as unknown as number, 10)
).toThrow(TypeError)
})

test('should throw a TypeError when exponent is not a positive integer', () => {
expect(() => binaryExponentiationIterative(2, -10)).toThrow(TypeError)
})

test('should return the result of the base number raised to the power of the exponent number', () => {
expect(binaryExponentiationIterative(2, 10)).toBe(1024)
expect(binaryExponentiationIterative(2, 0)).toBe(1)
expect(binaryExponentiationIterative(2, 1)).toBe(2)
expect(binaryExponentiationIterative(0, 10)).toBe(0)
expect(binaryExponentiationIterative(1, 10)).toBe(1)
})
})