Skip to content

Commit 91d27d6

Browse files
committed
fix: preserve integer precision in modular exponentiation
1 parent 5c39e87 commit 91d27d6

2 files changed

Lines changed: 14 additions & 3 deletions

File tree

‎Maths/ModularBinaryExponentiationRecursive.js‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,16 +6,18 @@
66
https://en.wikipedia.org/wiki/Exponentiation_by_squaring
77
*/
88

9+
const multiplyModulo = (a, b, m) => Number((BigInt(a) * BigInt(b)) % BigInt(m))
10+
911
const modularBinaryExponentiation = (a, n, m) => {
1012
// input: a: int, n: int, m: int
1113
// returns: (a^n) % m: int
1214
if (n === 0) {
13-
return 1
15+
return 1 % m
1416
} else if (n % 2 === 1) {
15-
return (modularBinaryExponentiation(a, n - 1, m) * a) % m
17+
return multiplyModulo(modularBinaryExponentiation(a, n - 1, m), a, m)
1618
} else {
1719
const b = modularBinaryExponentiation(a, n / 2, m)
18-
return (b * b) % m
20+
return multiplyModulo(b, b, m)
1921
}
2022
}
2123

‎Maths/test/ModularBinaryExponentiationRecursive.test.js‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,15 @@
11
import { modularBinaryExponentiation } from '../ModularBinaryExponentiationRecursive'
22

33
describe('modularBinaryExponentiation', () => {
4+
it.each([
5+
[9007199254740991, 3, 97, 12],
6+
[2147483646, 2, 2147483647, 1],
7+
[123456789, 12345, 1000000007, 614455772],
8+
[2, 0, 1, 0]
9+
])('should compute %i ** %i modulo %i exactly', (a, n, m, expected) => {
10+
expect(modularBinaryExponentiation(a, n, m)).toBe(expected)
11+
})
12+
413
it('should return the binary exponentiation', () => {
514
expect(modularBinaryExponentiation(2, 10, 17)).toBe(4)
615
})

0 commit comments

Comments
 (0)