/* 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" "scm.dairydemon.net/filifa/mathtools/internal/lib" ) var remainders []string var moduli []string func crt(cmd *cobra.Command, args []string) { if len(remainders) != len(moduli) { cobra.CheckErr("number of remainders and moduli do not match") } ns := make([]*big.Int, len(moduli)) rs := make([]*big.Int, len(remainders)) for i := range moduli { var ok bool ns[i], ok = new(big.Int).SetString(moduli[i], 10) if !ok { cobra.CheckErr("invalid input " + moduli[i]) } rs[i], ok = new(big.Int).SetString(remainders[i], 10) if !ok { cobra.CheckErr("invalid input " + remainders[i]) } } // TODO: support non-pairwise coprime moduli if !lib.ArePairwiseCoprime(ns) { err := fmt.Errorf("moduli %v are not pairwise coprime", moduli) cobra.CheckErr(err) } x, N := lib.CRTSolution(rs, ns) fmt.Println(x) fmt.Println(N) } // crtCmd represents the crt command var crtCmd = &cobra.Command{ Use: "crt -r R,R,[R, ...] -m M,M,[M, ...]", Short: "Solve a system of linear congruences with the Chinese remainder theorem", Long: `Solve a system of linear congruences by applying the Chinese remainder theorem. To use, provide the remainder R of each congruence, along with the corresponding modulus M for each congruence. For instance, mathtools crt -r 2,3,2 -m 3,5,7 will solve the system of congruences x = 2 (mod 3) x = 3 (mod 5) x = 2 (mod 7) `, Run: crt, } func init() { rootCmd.AddCommand(crtCmd) // Here you will define your flags and configuration settings. // Cobra supports Persistent Flags which will work for this command // and all subcommands, e.g.: // crtCmd.PersistentFlags().String("foo", "", "A help for foo") // Cobra supports local flags which will only run when this command // is called directly, e.g.: // crtCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") crtCmd.Flags().StringSliceVarP(&remainders, "remainders", "r", make([]string, 0), "remainders of congruences") crtCmd.MarkFlagRequired("remainders") crtCmd.Flags().StringSliceVarP(&moduli, "moduli", "m", make([]string, 0), "moduli of congruences") crtCmd.MarkFlagRequired("moduli") }