diff --git a/maths/binary_exponentiation_iterative.ts b/maths/binary_exponentiation_iterative.ts new file mode 100644 index 00000000..27559c5b --- /dev/null +++ b/maths/binary_exponentiation_iterative.ts @@ -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; +} diff --git a/maths/test/binary_exponentation_interative.test.ts b/maths/test/binary_exponentation_interative.test.ts new file mode 100644 index 00000000..4ee9e67c --- /dev/null +++ b/maths/test/binary_exponentation_interative.test.ts @@ -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) + }) +})