Course of Raku / Addendum 🆕 / Working with data / Numbers and mathematics / Exercises / Prime factorisation
Solution: Prime factorisation
Here is a possible solution to the task.
Code
my $n = 360;
my @factors;
for 2..$n -> $d {
while $n %% $d {
@factors.push($d);
$n div= $d;
}
}
say @factors;🦋 You can find the source code in the file prime-factors.raku.
Output
[2 2 2 3 3 5]Comments
For each candidate divisor
$d, the innerwhiledivides it out of$nas many times as it fits, pushing$deach time. Because the smaller factors are removed first, every$dthat still divides$nis guaranteed to be prime.$n div= $dis integer division back into$n; it shrinks the number until nothing but1is left.
Course navigation
← Prime factorisation | Greatest common divisor and least common multiple →