-
Notifications
You must be signed in to change notification settings - Fork 0
/
14.wsf
47 lines (45 loc) · 935 Bytes
/
14.wsf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# Project Euler
# Problem 14: Longest Collatz sequence
# https://projecteuler.net/problem=14
0 ^ readi retrieve 1-
0 ^ store
1
.loop:
2dup j< .end
^ call collatz_memo
2dup store
1 retrieve ^1 j< .longer
drop
.loop_next:
1+
jmp .loop
.end:
0 retrieve printi end
.longer:
1 swap store
0 ^1 store
jmp .loop_next
# collatz_memo returns the number of steps for n to reach 1 in the
# Collatz sequence, with counts for values less than n memoized. The
# sequence is defined as follows: if n is even, the next term is n/2,
# otherwise 3*n+1.
# (n -- steps)
collatz_memo:
0 ^1
.collatz_loop:
^ 1 j= .collatz_1
^ 2% jz .collatz_even
# .collatz_odd:
3* 1+ 2/
swap 2+ swap
jmp .collatz_next
.collatz_even:
2/
swap 1+ swap
.collatz_next:
^ ^2 j< .collatz_stored
jmp .collatz_loop
.collatz_stored:
retrieve + 1slide ret
.collatz_1:
2slide ret