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 primessequence listof primes
my @primes := 2, { next_prime($^a) } ... *;
 
Line 82:
multi factors(Int $remainder is copy) {
gather for @primes -> $factor {
 
last# if $remainder ==< 1;factor², we're done
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 /div= $factor) === 1;
}
last if $remainder == 1;
}
}
Line 95 ⟶ 101:
# array containing that number's factors, and then
# formats and displays them.
say "$_: ", factors($_).join(" x ") for 1..*;</lang>
 
The first twenty numbers:
Line 102 ⟶ 108:
2: 2
3: 3
4: 2 x 2
5: 5
6: 2 x 3
7: 7
8: 2 x 2 x 2
9: 3 x 3
10: 2 x 5
11: 11
12: 2 x 2 x 3
13: 13
14: 2 x 7
15: 3 x 5
16: 2 x 2 x 2 x 2
17: 17
18: 2 x 3 x 3
19: 19
20: 2 x 2 x 5</pre>
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&nbsp;6.) Note the use of <tt>gather</tt>/<tt>take</tt> as the final statement in the function, which is a common Perl&nbsp;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&nbsp;6 does Unicode natively.
 
=={{header|PicoLisp}}==
Anonymous user