while loops in Mojo
A Collatz walk: loop until the condition finally gives way.
def main():
var n = 27
var steps = 0
while n != 1:
if n % 2 == 0:
n //= 2
else:
n = 3 * n + 1
steps += 1
print("27 reaches 1 in", steps, "steps")
How it works
while n != 1:keeps going until the sequence lands on one.- Even values halve with
//=, and odd values take3 * n + 1. stepscounts how many iterations that took.
Keywords and builtins used here
defelseifmainprintvarwhile
The run, in numbers
- Lines
- 10
- Characters to type
- 145
- Tokens
- 53
- Three-star pace
- 90 tpm
At the three-star pace of 90 tokens a minute, this run takes about 35 seconds.
Step 2 of 5 in Flow control, step 8 of 26 in Language basics.