/* 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 lib import ( "errors" "math/big" ) /* SqrtRepetend returns the repetend of the continued fraction of sqrt(x). It returns an error if x is a perfect square. */ func SqrtRepetend(x *big.Int) ([]*big.Int, error) { m := big.NewInt(0) d := big.NewInt(1) a0 := new(big.Int).Sqrt(x) s := new(big.Int).Exp(a0, big.NewInt(2), nil) if x.Cmp(s) == 0 { return nil, errors.New("input is a perfect square") } repetend := make([]*big.Int, 0) a := new(big.Int).Set(a0) twoa0 := new(big.Int).Mul(big.NewInt(2), a0) for a.Cmp(twoa0) != 0 { // m = d * a - m tmp := new(big.Int) m.Sub(tmp.Mul(d, a), m) // d = (x - m^2) // d tmp.Exp(m, big.NewInt(2), nil) d.Div(tmp.Sub(x, tmp), d) // a = (a0 + m) // d a.Div(tmp.Add(a0, m), d) repetend = append(repetend, new(big.Int).Set(a)) } return repetend, nil } func cycle(seq []*big.Int) <-chan *big.Int { ch := make(chan *big.Int) n := len(seq) go func() { for i := 0; true; i = (i + 1) % n { ch <- seq[i] } }() return ch } /* GaussianBrackets returns a channel that outputs the sequence [], [a1], [a1, a2], ... where each value comes from the input channel and [] denotes Gaussian brackets. */ func GaussianBrackets(ch <-chan *big.Int) <-chan *big.Int { out := make(chan *big.Int) xprev := big.NewInt(0) x := big.NewInt(1) go func() { tmp := new(big.Int) for a := range ch { out <- x tmp.Mul(a, x) tmp.Add(tmp, xprev) xprev.Set(x) x = new(big.Int).Set(tmp) } }() return out } /* CFracConvergents returns a channel that outputs convergents of a periodic continued fraction with initial term a0 and repetend stored in denoms. */ func CFracConvergents(a0 *big.Int, denoms []*big.Int) <-chan *big.Rat { hc := cycle(denoms) _ = <-hc hch := GaussianBrackets(hc) kc := cycle(denoms) kch := GaussianBrackets(kc) _ = <-kch a := new(big.Rat).SetInt(a0) out := make(chan *big.Rat) go func() { for { h, k := <-hch, <-kch r := new(big.Rat).SetFrac(h, k) r.Add(r, a) out <- r } }() return out }