Anonymous user
Count in factors: Difference between revisions
→{{header|Perl 6}}: rewrite more idiomatically, with explanations
(→{{header|D}}: add D) |
(→{{header|Perl 6}}: rewrite more idiomatically, with explanations) |
||
Line 57:
The first two <tt>multi prime</tt> lines are adapted from Perl 6's entry at [[Primality by Trial Division]].
<lang perl6>multi prime
$n %% none 2, 3, *+2 ...^ * > sqrt $n;
}
multi
repeat until prime($check) { $check += 2 }▼
▲sub next_prime(Int $start --> Int) {
▲ until prime($check) { $check += 2 }
return $check;
}
# binding to an array memoizes primes list
my @primes := 2,
multi
multi factors(Int $remainder is copy) {
gather for @primes -> $factor {
# How many times can we divide by this prime?
while $remainder %% $factor {
▲multi factor(Int $toFactor)
last if ($remainder /= $factor) == 1;
}
last if $remainder == 1;
▲ # We found our next factor.
}
}
say "$_: ", factors($_).join(" x ") for 1..*;</lang>
The first twenty numbers:
Line 131 ⟶ 107:
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 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.
=={{header|PicoLisp}}==
|