snippets/euler/collatz-gforth.fs


\ Euler problem 14 in ANS Forth: 64-bit only.

: even?         2 mod 0= ; 
: collatz       dup even? if 2/ else 3 * 1+ then ;
: valid?        1 > ;
: collatz#      1 >r begin dup valid? while collatz r> 1+ >r repeat drop r> ;

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

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

: solve         0 largest ! 0 start ! (solve) start @ ;
: go            1000000 solve . ;


download original