gocollatz/collatz/calculator.go
Lars Mikal Rogne a9420a1a07
Initial commit
2024-04-24 19:35:43 +02:00

55 lines
1023 B
Go

package collatz
import (
"collatz/io"
"fmt"
"log"
"math/big"
)
type Calculator struct {
parser *io.Cliargs
three *big.Int
two *big.Int
one *big.Int
}
func NewCalculator(parser *io.Cliargs) Calculator {
r := Calculator{
parser: parser,
three: new(big.Int).SetInt64(3),
two: new(big.Int).SetInt64(2),
one: new(big.Int).SetInt64(1),
}
return r
}
func (o Calculator) Collatz() {
err := o.parser.Parse()
if err != nil {
log.Panicf("Couldn't parse input: %s\n", err)
}
number := o.parser.GetNumber()
fmt.Print(number.Text(10))
o.nextNumber(number)
fmt.Println()
}
func (o Calculator) nextNumber(in *big.Int) {
if in.Cmp(o.one) < 0 {
log.Panicln("Must be greater than 0")
}
if in.Cmp(o.one) == 0 {
return
}
var newNumber *big.Int
if new(big.Int).And(in, o.one).Cmp(o.one) == 0 {
newNumber = new(big.Int).Add(new(big.Int).Mul(in, o.three), o.one)
} else {
newNumber = new(big.Int).Div(in, o.two)
}
fmt.Printf(" -> %s", newNumber.Text(10))
o.nextNumber(newNumber)
}