Jump to content

Count in factors: Difference between revisions

→‎{{header|Perl 6}}: rewrite more idiomatically, with explanations
(→‎{{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 (Int $n -->where Bool( $n <= 1)) { False }
multi factorprime(Int $toFactorn --> Bool) {
$n %% none 2, 3, *+2 ...^ * > sqrt $n;
}
 
multi prime next_prime(Int2) $n{ where3 ( $n <= 1)) {}
submulti next_prime(Int $startcheck is copy --> Int) {
False;
repeat until prime($check) { $check += 2 }
}
 
sub next_prime(Int $start --> Int) {
my $check = $start + 1;
if $check %% 2 and $check > 2 { ++$check }
 
until prime($check) { $check += 2 }
 
return $check;
}
 
# binding to an array memoizes primes list
my @primes := 2, -> $a { next_prime($^a) } ... *;
 
multi factorfactors(Int1) $inFactor where ( $inFactor =={ 1 ) )}
multi factors(Int $remainder is copy) {
{
gather for @primes -> $factor {
(1);
# How many times can we divide by this prime?
}
while $remainder %% $factor {
 
# We found our nexttake $factor.;
multi factor(Int $toFactor)
last if ($remainder /= $factor) == 1;
{
}
my $currentRemainder = $toFactor;
last if $remainder == 1;
 
my @factors;
 
# Iterate through our primes until we find a prime number that's a factor of $currentRemainder;
until 1 == $currentRemainder {
my $primeIndex = 0;
 
# Find a factor of our current remainder.
until $currentRemainder %% @primes[$primeIndex] { ++$primeIndex }
 
# We found our next factor.
@factors.push(@primes[$primeIndex]);
 
# Some bookkeeping.
$currentRemainder /= @primes[$primeIndex];
}
 
@factors;
}
 
say "$_: ", factors($_).join(" x ") for 1..*;</lang>
for 1..* {
print "$_: ";
say factor($_).join(" x ");
}</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&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.
 
=={{header|PicoLisp}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.