optimize a bunch

This commit is contained in:
filifa 2025-08-19 22:35:15 -04:00
parent d12a5a492a
commit 7d554fb945
1 changed files with 21 additions and 22 deletions

View File

@ -28,40 +28,39 @@ import (
var modulus string var modulus string
var tpf []string var tpf []string
func totient(n *big.Int) *big.Int {
total := big.NewInt(0)
for a := big.NewInt(1); a.Cmp(n) == -1; a.Add(a, big.NewInt(1)) {
gcd := new(big.Int).GCD(nil, nil, a, n)
if gcd.Cmp(big.NewInt(1)) == 0 {
total.Add(total, big.NewInt(1))
}
}
return total
}
func computeNaive(modulus *big.Int) (*big.Int, error) { func computeNaive(modulus *big.Int) (*big.Int, error) {
if modulus.Cmp(big.NewInt(1)) == 0 { if modulus.Cmp(big.NewInt(1)) == 0 {
return big.NewInt(0), nil return big.NewInt(0), nil
} }
coprimes := make(map[string]bool) phi := totient(modulus)
for a := big.NewInt(1); a.Cmp(modulus) == -1; a.Add(a, big.NewInt(1)) {
gcd := new(big.Int).GCD(nil, nil, a, modulus) for g := big.NewInt(1); g.Cmp(modulus) == -1; g.Add(g, big.NewInt(1)) {
if gcd.Cmp(big.NewInt(1)) != 0 { tmp := new(big.Int).GCD(nil, nil, g, modulus)
if tmp.Cmp(big.NewInt(1)) != 0 {
continue continue
} }
coprimes[a.Text(10)] = true e := new(big.Int).Set(g)
} var k *big.Int
for k = big.NewInt(1); e.Cmp(big.NewInt(1)) != 0; k.Add(k, big.NewInt(1)) {
for g := big.NewInt(1); g.Cmp(modulus) == -1; g.Add(g, big.NewInt(1)) {
e := big.NewInt(1)
exps := make(map[string]big.Int)
for k := big.NewInt(1); k.Cmp(modulus) == -1; k.Add(k, big.NewInt(1)) {
e.Mul(e, g) e.Mul(e, g)
e.Mod(e, modulus) e.Mod(e, modulus)
exps[e.Text(10)] = *k
} }
isPrimitive := true if k.Cmp(phi) == 0 {
for a := range coprimes {
_, ok := exps[a]
if !ok {
isPrimitive = false
break
}
}
if isPrimitive {
return g, nil return g, nil
} }
} }