← All examples

Prime numbers

Collect every prime up to 30. Shows a helper function, a while loop, and the immutable append pattern (each append returns a new array).

fn isPrime(n: int): bool {
    if n < 2 {
        return false
    }
    let i: int = 2
    while i * i <= n {
        if n % i == 0 {
            return false
        }
        i = i + 1
    }
    return true
}

let primes: int[] = []
let candidate: int = 2
while candidate <= 30 {
    if isPrime(candidate) {
        primes = append(primes, candidate)
    }
    candidate = candidate + 1
}

print("Found " + toString(len(primes)) + " primes:")
for p in primes {
    print("  " + toString(p))
}
#functions#arrays#loops · View as Markdown