diff --git a/Maths/ModularBinaryExponentiationRecursive.js b/Maths/ModularBinaryExponentiationRecursive.js index 54665a3142..227a96042a 100644 --- a/Maths/ModularBinaryExponentiationRecursive.js +++ b/Maths/ModularBinaryExponentiationRecursive.js @@ -6,16 +6,18 @@ https://en.wikipedia.org/wiki/Exponentiation_by_squaring */ +const multiplyModulo = (a, b, m) => Number((BigInt(a) * BigInt(b)) % BigInt(m)) + const modularBinaryExponentiation = (a, n, m) => { // input: a: int, n: int, m: int // returns: (a^n) % m: int if (n === 0) { - return 1 + return 1 % m } else if (n % 2 === 1) { - return (modularBinaryExponentiation(a, n - 1, m) * a) % m + return multiplyModulo(modularBinaryExponentiation(a, n - 1, m), a, m) } else { const b = modularBinaryExponentiation(a, n / 2, m) - return (b * b) % m + return multiplyModulo(b, b, m) } } diff --git a/Maths/test/ModularBinaryExponentiationRecursive.test.js b/Maths/test/ModularBinaryExponentiationRecursive.test.js index 9758d0ed1d..b62517f11a 100644 --- a/Maths/test/ModularBinaryExponentiationRecursive.test.js +++ b/Maths/test/ModularBinaryExponentiationRecursive.test.js @@ -1,6 +1,15 @@ import { modularBinaryExponentiation } from '../ModularBinaryExponentiationRecursive' describe('modularBinaryExponentiation', () => { + it.each([ + [9007199254740991, 3, 97, 12], + [2147483646, 2, 2147483647, 1], + [123456789, 12345, 1000000007, 614455772], + [2, 0, 1, 0] + ])('should compute %i ** %i modulo %i exactly', (a, n, m, expected) => { + expect(modularBinaryExponentiation(a, n, m)).toBe(expected) + }) + it('should return the binary exponentiation', () => { expect(modularBinaryExponentiation(2, 10, 17)).toBe(4) })