Count in factors: Difference between revisions
Content added Content deleted
m (→{{header|Perl 6}}: remove some extraneous punctuation) |
(→{{header|Perl 6}}: A more symbolic implementation; factors are returned as an array, and formatted by the caller to factor().) |
||
Line 5: | Line 5: | ||
=={{header|Perl 6}}== |
=={{header|Perl 6}}== |
||
The 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 --> Bool) { |
<lang perl6>multi prime (Int $n --> Bool) { |
||
$n %% none 2, 3, *+2 ...^ * > sqrt $n; |
$n %% none 2, 3, *+2 ...^ * > sqrt $n; |
||
Line 16: | Line 16: | ||
sub next_prime(Int $start --> Int) { |
sub next_prime(Int $start --> Int) { |
||
my $check = $start + 1; |
my $check = $start + 1; |
||
if $check %% 2 and $check > 2 { ++$check } |
if $check %% 2 and $check > 2 { ++$check } |
||
until prime($check) { $check += 2 } |
until prime($check) { $check += 2 } |
||
Line 25: | Line 25: | ||
my @primes := 2, -> $a { next_prime($a) } ... *; |
my @primes := 2, -> $a { next_prime($a) } ... *; |
||
multi factor(Int $inFactor where ( $inFactor == 1 ) ) |
|||
say "1: 1"; |
|||
{ |
|||
(1); |
|||
} |
|||
multi factor(Int $toFactor) |
|||
⚫ | |||
{ |
|||
⚫ | |||
my $currentRemainder = $toFactor; |
|||
#say "L1 ... $_"; |
|||
⚫ | |||
my $currentProduct = 1; |
|||
# It's not prime? Find its prime factors. |
|||
⚫ | |||
⚫ | |||
my $prime_index = 0; |
|||
⚫ | |||
my @factors; |
|||
⚫ | |||
my $factor = @primes[$prime_index]; |
|||
⚫ | |||
if $currentProduct == 1 { print $factor } else { print " x $factor" } |
|||
⚫ | |||
⚫ | |||
# |
# Find a factor of our current remainder. |
||
⚫ | |||
$toFactor /= $factor; |
|||
$currentProduct *= $factor; |
|||
⚫ | |||
@factors.push(@primes[$primeIndex]); |
|||
# Some bookkeeping. |
|||
$currentRemainder /= @primes[$primeIndex]; |
|||
} |
} |
||
say ""; |
|||
@factors; |
|||
} |
|||
⚫ | |||
{ |
|||
⚫ | |||
say factor($_).join(" x "); |
|||
}</lang> |
}</lang> |
||