mathtools/cmd/modInverse.go

78 lines
2.3 KiB
Go
Raw Permalink Normal View History

2025-09-07 03:23:48 +00:00
/*
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 <http://www.gnu.org/licenses/>.
*/
package cmd
import (
"fmt"
"math/big"
"github.com/spf13/cobra"
)
var modInverseG string
var modInverseM string
func modInverse(cmd *cobra.Command, args []string) {
g, ok := new(big.Int).SetString(modInverseG, 10)
if !ok {
cobra.CheckErr("invalid input " + modInverseG)
}
n, ok := new(big.Int).SetString(modInverseM, 10)
if !ok {
cobra.CheckErr("invalid input " + modInverseM)
}
z := new(big.Int)
res := z.ModInverse(g, n)
if res == nil {
cobra.CheckErr("cannot find a modular inverse: " + modInverseG + " is not relatively prime to modulus " + modInverseM)
} else {
fmt.Println(z)
}
}
// modInverseCmd represents the modInverse command
var modInverseCmd = &cobra.Command{
2025-09-18 01:02:05 +00:00
Use: "mod-inverse -g N -m N",
2025-09-07 03:23:48 +00:00
Short: "Compute a modular inverse",
2025-09-18 01:02:05 +00:00
Long: `Compute a modular inverse.
Given a base g and modulus m, compute a value x such that gx = 1 (mod m). A solution only exists if g and m are coprime.`,
Run: modInverse,
2025-09-07 03:23:48 +00:00
}
func init() {
rootCmd.AddCommand(modInverseCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// modInverseCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// modInverseCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
modInverseCmd.Flags().StringVarP(&modInverseG, "base", "g", "", "integer to compute modular inverse of")
modInverseCmd.MarkFlagRequired("base")
modInverseCmd.Flags().StringVarP(&modInverseM, "modulus", "m", "", "modulus")
modInverseCmd.MarkFlagRequired("modulus")
}