create internal library
This commit is contained in:
parent
37f40b25b4
commit
8e71cc87e5
|
|
@ -17,46 +17,14 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"math/big"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"scm.dairydemon.net/filifa/mathtools/internal/lib"
|
||||
)
|
||||
|
||||
func computeSqrtRepetend(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 sqrtRepetend(cmd *cobra.Command, args []string) {
|
||||
x := new(big.Int)
|
||||
|
||||
|
|
@ -67,7 +35,7 @@ func sqrtRepetend(cmd *cobra.Command, args []string) {
|
|||
continue
|
||||
}
|
||||
|
||||
repetend, err := computeSqrtRepetend(x)
|
||||
repetend, err := lib.SqrtRepetend(x)
|
||||
if err != nil {
|
||||
log.Print(s + " is a perfect square")
|
||||
continue
|
||||
|
|
|
|||
|
|
@ -0,0 +1,38 @@
|
|||
package lib
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"math/big"
|
||||
)
|
||||
|
||||
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
|
||||
}
|
||||
Loading…
Reference in New Issue