The Extended Chinese Remainder Theorem is an algorithm that checks if
and finds such an integer if there exists for integers and postive integers in time and space.
Algorithm
Lemma
Proof
Applying Bézout’s Identity yields
- Apply the Euclidean Algorithm to find .
-
- If , applying the lemma yields that no solution exists.
- Otherwise, apply the Extended Euclidean Algorithm to find a pair of integers and such that , then is an integer such that .
This algorithm solves the problem in time and space.
std::optional<int> excrt(const std::array<int, 2> &a, const std::array<int, 2> &m) {
int gcd = std::gcd(m[0], m[1]);
if ((a[1] - a[0]) % gcd != 0) {
return std::nullopt;
}
return m[0] * (a[1] - a[0]) / gcd * exgcd(m[0], m[1]).first + a[0];
}