I want to solve linear and quadratic modular equations in Haskell in one variable. The way I am doing it right now is by putting x = [1..]
in the equation one by one and finding the remainder (expr `rem` p == 0
, if the equation is modulo p
(not necessarily a prime) where expr
has the variable x
). I believe this is a very inefficient process. So is there any better way to do it?
Modular equations in Haskell
Asked Answered
Solving modular quadratic equations involves combining:
- the Tonelli-Shanks algorithm
- the Chinese Remainder Theorem
- and the quadratic formula (i.e. completing the square)
For Haskell the arithmoi package has implementations of these algorithms. In particular, see the chineseRemainder, sqrtModP and sqrtModPP functions.
Here you can find some worked examples:
Be very careful with the
arithmoi
package. It has at least one bug in its prime sieve code that causes intermittent segmentation faults. The code is extremely hairy and poorly documented, and despite the package having a new maintainer there are no signs that it will improve any time soon. –
Azurite © 2022 - 2024 — McMap. All rights reserved.
ax+b = c (mod n)
you needx = (c-b)*a^-1 (mod n)
wherea^-1
is the modular inverse ofa
modn
. This will exist if and only ifa
andn
are relatively prime, in which case the extended Euclidean algorithm can compute it: en.wikipedia.org/wiki/… – Nine