Skip to content
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
8 changes: 5 additions & 3 deletions Maths/ModularBinaryExponentiationRecursive.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

Expand Down
9 changes: 9 additions & 0 deletions Maths/test/ModularBinaryExponentiationRecursive.test.js
Original file line number Diff line number Diff line change
@@ -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)
})
Expand Down