implement -t flag

This commit is contained in:
filifa 2025-08-20 00:51:51 -04:00
parent 00a7d213d3
commit a7ee29df8e
1 changed files with 42 additions and 3 deletions

View File

@ -73,8 +73,44 @@ func computeNaive(modulus *big.Int) (*big.Int, error) {
return nil, errors.New("no primitive root") return nil, errors.New("no primitive root")
} }
func computeFromFactors(modulus *big.Int, tpf []string) *big.Int { func computeFromFactors(modulus *big.Int, tpf []string) (*big.Int, error) {
return nil phi := big.NewInt(1)
factors := make(map[string]bool)
for _, s := range tpf {
p, ok := new(big.Int).SetString(s, 10)
if !ok {
return nil, errors.New("invalid input " + s)
}
phi.Mul(phi, p)
factors[p.Text(10)] = true
}
for g := big.NewInt(1); g.Cmp(modulus) == -1; g.Add(g, big.NewInt(1)) {
gcd := new(big.Int).GCD(nil, nil, g, modulus)
if gcd.Cmp(big.NewInt(1)) != 0 {
continue
}
isPrimitive := true
for p := range factors {
e := new(big.Int)
f, _ := new(big.Int).SetString(p, 10)
k := new(big.Int).Div(phi, f)
e.Exp(g, k, modulus)
if e.Cmp(big.NewInt(1)) == 0 {
isPrimitive = false
break
}
}
if isPrimitive {
return g, nil
}
}
return nil, errors.New("no primitive root")
} }
func primitiveRoot(cmd *cobra.Command, args []string) { func primitiveRoot(cmd *cobra.Command, args []string) {
@ -91,7 +127,10 @@ func primitiveRoot(cmd *cobra.Command, args []string) {
log.Fatal(err) log.Fatal(err)
} }
} else { } else {
root = computeFromFactors(m, tpf) root, err = computeFromFactors(m, tpf)
if err != nil {
log.Fatal(err)
}
} }
fmt.Println(root) fmt.Println(root)