mathtools/cmd/pell.go

86 lines
2.1 KiB
Go
Raw Normal View History

2025-09-05 23:02:15 +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"
"scm.dairydemon.net/filifa/mathtools/internal/lib"
)
var pellCoeff string
func pell(cmd *cobra.Command, args []string) {
d, ok := new(big.Int).SetString(pellCoeff, 10)
if !ok {
cobra.CheckErr("invalid input " + args[0])
}
a0 := new(big.Int).Sqrt(d)
repetend, err := lib.SqrtRepetend(d)
if err != nil {
cobra.CheckErr(pellCoeff + " is a perfect square")
}
r := len(repetend)
var period int
if r%2 == 0 {
period = r
} else {
period = 2 * r
}
2025-09-06 03:52:40 +00:00
ch := cFracConvergents(a0, repetend)
2025-09-05 23:02:15 +00:00
for i := 1; true; i = (i + 1) % period {
2025-09-06 03:52:40 +00:00
r := <-ch
if i == period-1 {
2025-09-06 03:52:40 +00:00
fmt.Println(r.Num(), r.Denom())
2025-09-05 23:02:15 +00:00
}
}
}
// pellCmd represents the pell command
var pellCmd = &cobra.Command{
Use: "pell",
Short: "Find solutions to a Pell equation",
Long: `Find solutions to a Pell equation.`,
Run: pell,
}
func init() {
rootCmd.AddCommand(pellCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// pellCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// pellCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
pellCmd.Flags().StringVarP(&pellCoeff, "coefficient", "d", "", "coefficient")
pellCmd.MarkFlagRequired("coefficient")
// TODO: add support for generalized Pell equations
}