Skip to content

Commit 1e3b32f

Browse files
authored
Fix modular_inverse not handling m == 1 correctly (#16)
1 parent a048e9e commit 1e3b32f

File tree

2 files changed

+10
-1
lines changed

2 files changed

+10
-1
lines changed

.spec/math/modular_inverse_spec.lua

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,13 @@ describe("Modular inverse", function()
1313
it("should handle cases when inputs are not co-prime", function()
1414
assert.equal(nil, modular_inverse(2, 2))
1515
assert.equal(nil, modular_inverse(5, 15))
16+
end)
17+
18+
it("should handle cases when modulus is 1", function()
19+
assert.equal(nil, modular_inverse(-1, 1))
1620
assert.equal(nil, modular_inverse(0, 1))
21+
assert.equal(nil, modular_inverse(1, 1))
22+
assert.equal(nil, modular_inverse(2, 1))
1723
end)
1824

1925
it("should throw error when modulus is zero", function()

src/math/modular_inverse.lua

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,11 @@ return function(
88
m -- modulus
99
)
1010
assert(m > 0, "modulus must be positive")
11+
if m == 1 then
12+
return nil
13+
end
1114
local gcd, x, _ = extended_gcd(a % m, m)
12-
if a ~= 0 and gcd == 1 then
15+
if gcd == 1 then
1316
-- Ensure that result is in (0, m)
1417
return x % m
1518
end

0 commit comments

Comments
 (0)