Course of Raku / Addendum 🆕 / Working with data / Numbers and mathematics / Exercises / Perfect numbers
Solution: Perfect numbers
Here is a possible solution to the task.
Code
my @perfect = (1..30).grep: -> $n {
$n == [+] (1..^$n).grep($n %% *)
};
say @perfect;🦋 You can find the source code in the file perfect-numbers.raku.
Output
[6 28]Comments
(1..^$n).grep($n %% *)keeps the numbers below$nthat divide it evenly — its proper divisors. The%% *is a Whatever function that tests divisibility.[+]sums those divisors, and the outergrepkeeps only the numbers that are equal to that sum.