5 ms·
Oh, and I just tested this on play.golang.org, and I had wrong results because a was too small, so we need to manually set it to an uint64: package main i
by rakoo 13y ago
Oh, and I just tested this on play.golang.org, and I had wrong results because a was too small, so we need to manually set it to an uint64:
package main
import (
"log"
)
func main() {
max := 1000000
var maxa int
var maxlength int
for a0 := 0; a0 < max; a0++ {
var length int
a := uint64(a0)
for a > 1 {
if a%2 == 0 {
a = a/2
} else {
a = (3 * a + 1) / 2
}
length++
}
if length > maxlength {
maxa = a0
maxlength = length
}
}
log.Println(maxlength, maxa)
}
Even more interestingly, this is even faster:
> time ./collatz
2013/12/01 13:59:06 329 837799
./collatz 0,27s user 0,00s system 99% cpu 0,276 total