Count in factors

From Rosetta Code
Revision as of 18:38, 23 December 2010 by MikeMol (talk | contribs) (Draft task, initial example. I'm not a Perl 6 expert. The code can probably use some love.)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Count in factors is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

Write a program which counts up from 1, displaying each number as the multiplication of its prime factors. For the purpose of this task, may be shown as itself.

For examle, is prime, so it would be shown as itself. is not prime; it would be shown as . Likewise, 2144 is not prime; it would be shown as .

Perl 6

The two multi prime lines are adapted from Perl 6's entry at Primality by Trial Division. <lang perl6>multi prime (Int $n --> Bool) {

   $n %% none 2, 3, *+2 ...^ * > sqrt $n;

}

multi prime (Int $n where ( $n <= 1)) {

   False;

}

sub next_prime(Int $start --> Int) {

   my $check = $start + 1;
   if ( $check %% 2 and $check > 2 ) { ++$check }
   until(prime($check)) { $check += 2 }
   return $check;

}

my @primes := 2, -> $a { next_prime($a) } ... *;

say "1: 1";

for(2..*) {

 print "$_: ";
 #say "L1 ... $_";
 my $toFactor = $_;
 my $currentProduct = 1;
 # It's not prime? Find its prime factors.
 until(1 == $toFactor)
 {
   # Iterate through our primes until we find a prime number that's a factor of $toFactor.
   my $prime_index = 0;
   
   until( $toFactor %% @primes[$prime_index]) { ++$prime_index };
   # We found our next factor.
   my $factor = @primes[$prime_index];
   if($currentProduct == 1) { print $factor } else { print " x $factor" }
   # Bookkeeping, to keep track of how far we have to go.
   $toFactor /= $factor;
   $currentProduct *= $factor;
 }
 say "";

}</lang>

The first twenty numbers:

1: 1
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