primes.raku
A short number-theory tour.
A tour through some number theory: a lazy Sieve-of-Eratosthenes sequence, factorials and Mersenne primes computed in arbitrary precision (no 64-bit ceiling), and Collatz stopping times.
The program
Edit it and press Run — it executes in your browser.
#!/usr/bin/env raku
# A short tour of number theory, leaning on Raku's arbitrary-precision
# integers (there is no 64-bit ceiling — factorials and Mersenne numbers
# grow to whatever size they need) and the lazy sequence operator `...`.
# Sieve of Eratosthenes as a lazy, self-referential sequence: each new
# prime is the next number not divisible by any prime already found.
my @primes = lazy gather {
my @seen;
my $n = 2;
loop {
unless @seen.first: $n %% * {
@seen.push: $n;
take $n;
}
$n++;
}
}
say 'First 20 primes:';
say @primes[^20];
say '';
say 'Primes between 100 and 130:';
say @primes[^40].grep({ 100 <= $_ <= 130 });
# Arbitrary precision: factorials well past what a machine int could hold.
say '';
say 'Factorials:';
for 10, 25, 50 -> $n {
say " $n! = ", [*] 1 .. $n;
}
# Mersenne primes: numbers of the form 2^p - 1 that are themselves prime.
say '';
say 'Mersenne primes 2^p - 1 (p prime, p < 32):';
for @primes[^11] -> $p {
my $m = 2 ** $p - 1;
say " p=$p 2^{$p}-1 = $m" if $m.is-prime;
}
# The Collatz (3n+1) sequence: the stopping time for a few seeds.
sub collatz-steps($start) {
my $n = $start;
my $steps = 0;
while $n != 1 {
$n = $n %% 2 ?? $n div 2 !! 3 * $n + 1;
$steps++;
}
$steps;
}
say '';
say 'Collatz stopping times:';
for 6, 27, 97 -> $n {
say " $n reaches 1 in {collatz-steps($n)} steps";
}
Open in the playground ↗ Source on GitHub ↗
Output
First 20 primes:
(2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71)
Primes between 100 and 130:
(101 103 107 109 113 127)
Factorials:
10! = 3628800
25! = 15511210043330985984000000
50! = 30414093201713378043612608166064768844377641568960512000000000000
Mersenne primes 2^p - 1 (p prime, p < 32):
p=2 2^2-1 = 3
p=3 2^3-1 = 7
p=5 2^5-1 = 31
p=7 2^7-1 = 127
p=13 2^13-1 = 8191
p=17 2^17-1 = 131071
p=19 2^19-1 = 524287
p=31 2^31-1 = 2147483647
Collatz stopping times:
6 reaches 1 in 8 steps
27 reaches 1 in 111 steps
97 reaches 1 in 118 stepsFeature focus: lazy sequences, big Int.