refactor into multiplicativeOrder function

This commit is contained in:
filifa 2025-08-19 22:40:33 -04:00
parent 7d554fb945
commit 117b046be8
1 changed files with 13 additions and 8 deletions

View File

@ -40,6 +40,17 @@ func totient(n *big.Int) *big.Int {
return total return total
} }
func multiplicativeOrder(g *big.Int, modulus *big.Int) *big.Int {
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)) {
e.Mul(e, g)
e.Mod(e, modulus)
}
return k
}
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
@ -53,14 +64,8 @@ func computeNaive(modulus *big.Int) (*big.Int, error) {
continue continue
} }
e := new(big.Int).Set(g) order := multiplicativeOrder(g, modulus)
var k *big.Int if order.Cmp(phi) == 0 {
for k = big.NewInt(1); e.Cmp(big.NewInt(1)) != 0; k.Add(k, big.NewInt(1)) {
e.Mul(e, g)
e.Mod(e, modulus)
}
if k.Cmp(phi) == 0 {
return g, nil return g, nil
} }
} }