Count in factors: Difference between revisions

Content deleted Content added
→‎{{header|Perl 6}}: rewrite more idiomatically, with explanations
→‎{{header|Perl 6}}: Added comments for function groupings.
Line 57: Line 57:


The first two <tt>multi prime</tt> lines are adapted from Perl 6's entry at [[Primality by Trial Division]].
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 ( $n <= 1)) { False }
<lang perl6># Multi function to test a number for primality.
# Which function body is called depends on which one's
# criteria most-specifically matches the given argument
# values.
multi prime(Int $n where ( $n <= 1)) { False }
multi prime(Int $n --> Bool) {
multi prime(Int $n --> Bool) {
$n %% none 2, 3, *+2 ...^ * > sqrt $n;
$n %% none 2, 3, *+2 ...^ * > sqrt $n;
}
}



# Returns the next prime greater than the value given.
multi next_prime(2) { 3 }
multi next_prime(2) { 3 }
multi next_prime(Int $check is copy --> Int) {
multi next_prime(Int $check is copy --> Int) {
Line 71: Line 77:
my @primes := 2, { next_prime($^a) } ... *;
my @primes := 2, { next_prime($^a) } ... *;


# Finds the factors of the given argument.
multi factors(1) { 1 }
multi factors(1) { 1 }
multi factors(Int $remainder is copy) {
multi factors(Int $remainder is copy) {
Line 83: Line 90:
}
}


# An infinite loop, from 1 incrementing upward.
# calls factor() with each of 1, 2, 3, etc., receives an
# array containing that number's factors, and then
# formats and displays them.
say "$_: ", factors($_).join(" x ") for 1..*;</lang>
say "$_: ", factors($_).join(" x ") for 1..*;</lang>