don't recompute coprime numbers over and over

This commit is contained in:
filifa 2025-08-19 22:22:16 -04:00
parent a7547fc0eb
commit d12a5a492a
1 changed files with 12 additions and 7 deletions

View File

@ -33,6 +33,16 @@ func computeNaive(modulus *big.Int) (*big.Int, error) {
return big.NewInt(0), nil return big.NewInt(0), nil
} }
coprimes := make(map[string]bool)
for a := big.NewInt(1); a.Cmp(modulus) == -1; a.Add(a, big.NewInt(1)) {
gcd := new(big.Int).GCD(nil, nil, a, modulus)
if gcd.Cmp(big.NewInt(1)) != 0 {
continue
}
coprimes[a.Text(10)] = true
}
for g := big.NewInt(1); g.Cmp(modulus) == -1; g.Add(g, big.NewInt(1)) { for g := big.NewInt(1); g.Cmp(modulus) == -1; g.Add(g, big.NewInt(1)) {
e := big.NewInt(1) e := big.NewInt(1)
exps := make(map[string]big.Int) exps := make(map[string]big.Int)
@ -43,13 +53,8 @@ func computeNaive(modulus *big.Int) (*big.Int, error) {
} }
isPrimitive := true isPrimitive := true
for a := big.NewInt(1); a.Cmp(modulus) == -1; a.Add(a, big.NewInt(1)) { for a := range coprimes {
gcd := new(big.Int).GCD(nil, nil, a, modulus) _, ok := exps[a]
if gcd.Cmp(big.NewInt(1)) != 0 {
continue
}
_, ok := exps[a.Text(10)]
if !ok { if !ok {
isPrimitive = false isPrimitive = false
break break