Julia Language Collatz sequence


Example

The while loop runs its body as long as the condition holds. For instance, the following code computes and prints the Collatz sequence from a given number:

function collatz(n)
    while n ≠ 1
        println(n)
        n = iseven(n) ? n ÷ 2 : 3n + 1
    end
    println("1... and 4, 2, 1, 4, 2, 1 and so on")
end

Usage:

julia> collatz(10)
10
5
16
8
4
2
1... and 4, 2, 1, 4, 2, 1 and so on

It is possible to write any loop recursively, and for complex while loops, sometimes the recursive variant is more clear. However, in Julia, loops have some distinct advantages over recursion:

  • Julia does not guarantee tail call elimination, so recursion uses additional memory and may cause stack overflow errors.
  • And further, for the same reason, a loop can have decreased overhead and run faster.