mathtools/cmd/isprime.go

78 lines
2.2 KiB
Go
Raw Normal View History

2025-08-12 23:08:20 +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"
"log"
"math/big"
"github.com/spf13/cobra"
)
var rounds uint
func isprime(cmd *cobra.Command, args []string) {
x := new(big.Int)
primes := make([]bool, len(args))
for i, s := range args {
_, ok := x.SetString(s, 10)
if !ok {
log.Fatal("invalid input " + s)
}
primes[i] = x.ProbablyPrime(int(rounds))
}
for _, b := range primes {
fmt.Println(b)
}
}
// isprimeCmd represents the isprime command
var isprimeCmd = &cobra.Command{
2025-08-12 23:25:28 +00:00
Use: "isprime N [N ...]",
2025-08-12 23:08:20 +00:00
Short: "Determine whether a number is prime",
2025-08-12 23:25:28 +00:00
Long: `Determine whether a number is prime.
This applies 10 iterations of the Miller-Rabin test and a Baillie-PSW test. Use
flags to change the number of Miller-Rabin iterations.
For inputs less than 2^64, results are 100% accurate. For larger numbers, there
is a small chance of falsely reporting a composite number as prime. That chance
can be reduced by applying more rounds of Miller-Rabin.`,
Args: cobra.MinimumNArgs(1),
Run: isprime,
2025-08-12 23:08:20 +00:00
}
func init() {
rootCmd.AddCommand(isprimeCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// isprimeCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// isprimeCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
2025-08-12 23:25:28 +00:00
isprimeCmd.Flags().UintVarP(&rounds, "rounds", "r", 10, "number of iterations of Miller-Rabin test")
2025-08-12 23:08:20 +00:00
}