A-M baby
This commit is contained in:
parent
764da6cbbb
commit
db842d013d
19005 changed files with 197040 additions and 7 deletions
16
Task/Modular-inverse/Haskell/modular-inverse.hs
Normal file
16
Task/Modular-inverse/Haskell/modular-inverse.hs
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
-- Extended Euclidean algorithm. Given non-negative a and b, return x, y and g
|
||||
-- such that ax + by = g, where g = gcd(a,b). Note that x or y may be negative.
|
||||
gcdExt a 0 = (1, 0, a)
|
||||
gcdExt a b = let (q, r) = a `quotRem` b
|
||||
(s, t, g) = gcdExt b r
|
||||
in (t, s - q * t, g)
|
||||
|
||||
-- Given a and m, return Just x such that ax = 1 mod m. If there is no such x
|
||||
-- return Nothing.
|
||||
modInv a m = let (i, _, g) = gcdExt a m
|
||||
in if g == 1 then Just (mkPos i) else Nothing
|
||||
where mkPos x = if x < 0 then x + m else x
|
||||
|
||||
main = do
|
||||
print $ 2 `modInv` 4
|
||||
print $ 42 `modInv` 2017
|
||||
Loading…
Add table
Add a link
Reference in a new issue