XLang Demo
XLang Home
XLang Quick Ref
Select Output type:
Execution + Errors/Warnings
Execution
Errors/Warnings
Runtime pseudo-code
All
Select Sample:
primes
matcher (precompute)
phrasebook (unbound)
hello world
ackermann
ackermann (iter)
bubblesort
fibonacci
fibonacci (iter)
quicksort
tower of hanoi
// This sample returns a list of the first N prime numbers. // Returns true if n is prime, false otherwise. // Since composite (non-prime) numbers are always the product of primes, we can determine if n is prime by checking // if it is divisible by any of the primes we've already found, less than or equal to the square root of n. bool isPrime(uint64 n, uint64[] primeList) { for (i := 0uz; i < primeList.len && primeList[i] * primeList[i] <= n; ++i) { if (n % primeList[i] == 0) { return false; } } return true; } uint64[] firstNPrimes(usize length) { uint64[] primeList; for (n := 2u64; primeList.len < length; ++n) { if (isPrime(n, primeList)) { primeList += n; } } return primeList; } int64 main() { // precomput primes static_assert(firstNPrimes(7).epoch == "precomp"); static_assert(firstNPrimes(0) == uint64[]{}); static_assert(firstNPrimes(1) == uint64[]{2}); static_assert(firstNPrimes(2) == uint64[]{2, 3}); static_assert(firstNPrimes(4) == uint64[]{2, 3, 5, 7}); static_assert(firstNPrimes(7) == uint64[]{2, 3, 5, 7, 11, 13, 17}); static_assert(firstNPrimes(20) == uint64[]{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71}); // print out firstNPrimes(7) std.println("First 7 primes:"); primes := firstNPrimes(7); for (i := 0uz; i < primes.len; ++i) { std.println(primes[i]); } }
Output Type: All