snippets/euler/collatz.fs


\ Euler problem 14 in SwiftForth.
\ 
\ Non-portable due to use of bigmath.f package [we need doubles].
\ => Also note that collatz sequence counts are expected to fit in a cell.
include %SwiftForth/lib/options/bigmath.f

package collatz
: dmod          postpone du/mod postpone 2drop ; immediate
: even?         2. dmod d0= ; 
: collatz       2dup even? if d2/ else 3. d* 1. d+ then ;
: valid?        2. d< 0= ;
: collatz#      1 >r begin 2dup valid? while collatz r> 1+ >r repeat 2drop r> ;

variable        largest     \ ...sequence length
variable        start       \ ...of sequence with maximum length

: note          start !  largest ! ;
: longer?       largest @ > ;
: (solve)       0 do i s>d collatz# dup longer? if i note else drop then loop ;

public
: solve         0 largest ! 0 start ! (solve) start @ ;
: go            1000000 solve . ;
end-package


download original