From 849df37a9663b712e86a42c890cfce717880faf8 Mon Sep 17 00:00:00 2001 From: filifa Date: Sat, 6 Sep 2025 23:23:48 -0400 Subject: [PATCH] add modular inverse command --- cmd/modInverse.go | 75 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 cmd/modInverse.go diff --git a/cmd/modInverse.go b/cmd/modInverse.go new file mode 100644 index 0000000..aed683c --- /dev/null +++ b/cmd/modInverse.go @@ -0,0 +1,75 @@ +/* +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 . +*/ +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{ + Use: "mod-inverse", + Short: "Compute a modular inverse", + Long: `Compute a modular inverse.`, + Run: modInverse, +} + +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") +}