/* Copyright © 2025 filifa This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ package lib import ( "math/big" ) func solveCRT(a1, n1, a2, n2 *big.Int) (*big.Int, *big.Int) { // use Bezout's identity to find m1, m2 such that m1*n1 + m2*n2 = 1 m1 := new(big.Int) m2 := new(big.Int) tmp := new(big.Int) tmp.GCD(m1, m2, n1, n2) // x = a1*m2*n2 + a2*m1*n1 x := new(big.Int).Set(a1) x.Mul(x, m2) x.Mul(x, n2) tmp.Set(a2) tmp.Mul(tmp, m1) tmp.Mul(tmp, n1) x.Add(x, tmp) N := new(big.Int).Set(n1) N.Mul(N, n2) x.Mod(x, N) return x, N } /* Given a system of congruences - defined by slices of remainders and moduli such that x = remainders[i] (mod moduli[i]) for each index i - CRTSolution outputs a solution to the system. */ func CRTSolution(remainders, moduli []*big.Int) (*big.Int, *big.Int) { n1 := new(big.Int) a1 := new(big.Int) for i, n2 := range moduli { a2 := remainders[i] if i == 0 { a1.Set(a2) n1.Set(n2) continue } a1, n1 = solveCRT(a1, n1, a2, n2) } return a1, n1 } /* ArePairwiseCoprime returns true if each pair of values in the input slice are coprime. */ func ArePairwiseCoprime(moduli []*big.Int) bool { z := new(big.Int) for i, a := range moduli { for _, b := range moduli[i+1:] { z.GCD(nil, nil, a, b) if z.Cmp(big.NewInt(1)) != 0 { return false } } } return true }