diff --git a/cmd/convergents.go b/cmd/convergents.go index 7d63c1d..aab1ba8 100644 --- a/cmd/convergents.go +++ b/cmd/convergents.go @@ -35,10 +35,14 @@ func cycle(seq []*big.Int) <-chan *big.Int { return ch } -func gaussianBrackets(x, xprev *big.Int, ch <-chan *big.Int) <-chan *big.Int { +func gaussianBrackets(ch <-chan *big.Int) <-chan *big.Int { out := make(chan *big.Int) + xprev := big.NewInt(0) + x := big.NewInt(1) + go func() { + out <- big.NewInt(1) for a := range ch { tmp := new(big.Int).Mul(a, x) tmp.Add(tmp, xprev) @@ -51,6 +55,32 @@ func gaussianBrackets(x, xprev *big.Int, ch <-chan *big.Int) <-chan *big.Int { return out } +func cFracConvergents(a0 *big.Int, denoms []*big.Int) <-chan *big.Rat { + f := cycle(denoms) + _ = <-f + g := cycle(denoms) + + hch := gaussianBrackets(f) + kch := gaussianBrackets(g) + _ = <-kch + + a := new(big.Rat).SetInt(a0) + + out := make(chan *big.Rat) + + go func() { + for { + r := new(big.Rat) + h, k := <-hch, <-kch + r.SetFrac(h, k) + r.Add(r, a) + out <- r + } + }() + + return out +} + func convergents(cmd *cobra.Command, args []string) { a0, ok := new(big.Int).SetString(args[0], 10) if !ok { @@ -66,13 +96,7 @@ func convergents(cmd *cobra.Command, args []string) { } } - hch := gaussianBrackets(a0, big.NewInt(1), cycle(denoms)) - kch := gaussianBrackets(big.NewInt(1), big.NewInt(0), cycle(denoms)) - - r := new(big.Rat) - for { - h, k := <-hch, <-kch - r.SetFrac(h, k) + for r := range cFracConvergents(a0, denoms) { fmt.Println(r) } } diff --git a/cmd/pell.go b/cmd/pell.go index 7630aed..6251da6 100644 --- a/cmd/pell.go +++ b/cmd/pell.go @@ -47,13 +47,12 @@ func pell(cmd *cobra.Command, args []string) { period = 2 * r } - hch := gaussianBrackets(a0, big.NewInt(1), cycle(repetend)) - kch := gaussianBrackets(big.NewInt(1), big.NewInt(0), cycle(repetend)) + ch := cFracConvergents(a0, repetend) for i := 1; true; i = (i + 1) % period { - h, k := <-hch, <-kch + r := <-ch if i == period-1 { - fmt.Println(h, k) + fmt.Println(r.Num(), r.Denom()) } } }