typestar

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

  1. while n != 1: keeps going until the sequence lands on one.
  2. Even values halve with //=, and odd values take 3 * n + 1.
  3. steps counts how many iterations that took.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 5 in Flow control, step 8 of 26 in Language basics.

← Previous Next →

while loops in other languages