Anonymous user
Count in factors: Difference between revisions
→{{header|Perl 6}}: a much faster algorithm
m (moved Counting in Factors to Counting in factors: capitalization policy) |
(→{{header|Perl 6}}: a much faster algorithm) |
||
Line 75:
}
# binding to an array memoizes
my @primes := 2, { next_prime($^a) } ... *;
Line 82:
multi factors(Int $remainder is copy) {
gather for @primes -> $factor {
if $factor * $factor > $remainder {
take($remainder) if $remainder > 1;
last;
}
# How many times can we divide by this prime?
while $remainder %% $factor {
take $factor;
last if ($remainder
}
▲ last if $remainder == 1;
}
}
Line 95 ⟶ 101:
# array containing that number's factors, and then
# formats and displays them.
say "$_: ", factors($_).join("
The first twenty numbers:
Line 102 ⟶ 108:
2: 2
3: 3
4: 2
5: 5
6: 2
7: 7
8: 2
9: 3
10: 2
11: 11
12: 2
13: 13
14: 2
15: 3
16: 2
17: 17
18: 2
19: 19
20: 2
Here we use a <tt>multi</tt> declaration with a constant parameter to match the degenerate case. We use <tt>copy</tt> parameters when we wish to reuse the formal parameter as a mutable variable within the function. (Parameters default to readonly in Perl 6.) Note the use of <tt>gather</tt>/<tt>take</tt> as the final statement in the function, which is a common Perl 6 idiom to set up a coroutine within a function to return a lazy list on demand.
The second <tt>last</tt> is a workaround since rakudo does not yet support loop exit via loop labels.
Note also the '✕' above is not ASCII 'x', but U+2715, MULTIPLICATION X. Perl 6 does Unicode natively.
=={{header|PicoLisp}}==
|