# --- 1. SETUP CONSTANTS ---
# We need a Loop Limit (M) and a One (O) for counters.
# We construct M using exponential doubling to save space.
# Set O to 1
INCREASE O
# Set M to 512 (2^9) to ensure we have enough loops for the sequence.
# 1 -> 2 -> 4 -> 8 ... -> 512
INCREASE M
REPEAT M TIMES (INCREASE M)
REPEAT M TIMES (INCREASE M)
REPEAT M TIMES (INCREASE M)
REPEAT M TIMES (INCREASE M)
REPEAT M TIMES (INCREASE M)
REPEAT M TIMES (INCREASE M)
REPEAT M TIMES (INCREASE M)
REPEAT M TIMES (INCREASE M)
REPEAT M TIMES (INCREASE M)
# Set Flag F to 1. F controls if the program is "Running".
# If F is 0, we stop doing work.
CLEAR F
INCREASE F
# --- 2. MAIN LOOP ---
# Repeats 512 times. Code inside only acts if F is 1.
REPEAT M TIMES (
# --- STEP A: PRINT CURRENT X ---
REPEAT F TIMES (
PRINT X
)
# --- STEP B: CHECK IF X IS 1 ---
# If X is 1, we are done. We must set F to 0.
# Optimization: We check "Is X == 1" in O(X) time, not O(X^2).
# S will be our "Is One" flag. Assume it is 1 initially.
CLEAR S
INCREASE S
# H will be "Has Run Once". Start at 0.
CLEAR H
# Loop X times.
# Iteration 1: H is 0. S stays 1. H becomes 1.
# Iteration 2+: H is 1. S becomes 0. H stays 1.
REPEAT X TIMES (
REPEAT H TIMES (CLEAR S)
CLEAR H
INCREASE H
)
# If S is still 1, then X was 1. We clear the main run flag F.
REPEAT S TIMES (CLEAR F)
# --- STEP C: CALCULATE NEXT NUMBER ---
# Only run if F is still 1 (meaning X was not 1)
REPEAT F TIMES (
# Copy X to Y for calculation
CLEAR Y
REPEAT X TIMES (INCREASE Y)
# Division by 2 and Modulo
# Q = Quotient, R = Remainder (0 or 1), E = Even Flag (1 or 0)
CLEAR Q
CLEAR R
CLEAR E
INCREASE E
# We iterate Y times (count up to X)
REPEAT Y TIMES (
# If R is 1, we are completing a pair -> Increase Quotient
REPEAT R TIMES (INCREASE Q)
# Swap R and E (Toggle Even/Odd state)
# T is a temp variable
CLEAR T
REPEAT R TIMES (INCREASE T)
CLEAR R
REPEAT E TIMES (INCREASE R)
CLEAR E
REPEAT T TIMES (INCREASE E)
)
# --- STEP D: APPLY COLLATZ RULES ---
CLEAR X
# If Even (E=1): X = Q
REPEAT E TIMES (
REPEAT Q TIMES (INCREASE X)
)
# If Odd (R=1): X = 3Y + 1
REPEAT R TIMES (
REPEAT Y TIMES (
INCREASE X
INCREASE X
INCREASE X
)
INCREASE X
)
)
)