mathtools/cmd/pell.go

90 lines
2.4 KiB
Go

/*
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
}
ch := lib.CFracConvergents(a0, repetend)
// TODO: consider breaking after finding the fundamental solution and using the recurrence relation to find the following solutions
for i := 1; true; i = (i + 1) % period {
r := <-ch
if i == period-1 {
fmt.Println(r.Num(), r.Denom())
}
}
}
// pellCmd represents the pell command
var pellCmd = &cobra.Command{
Use: "pell -d N",
Short: "Find solutions to a Pell equation",
Long: `Find integer solutions to a Pell equation x^2 - dy^2 = 1.
This will output solutions infinitely. Try piping to head to only output a certain number of solutions, like this:
mathtools pell -d 12 | head -n 5`,
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
}