http://qs1969.pair.com?node_id=877318

andmott has asked for the wisdom of the Perl Monks concerning the following question:

I'm taking a perl course, and my homework is the following:

"Write a one-liner that is the equivalent of the Unix factor program: it should print out all the prime factors of its input."

It seems a little bit much to ask in my opinion of a one-liner, but what do you think? Part of my question is whether this is a good quiz or not.

I haven't gotten to the one-liner part or 'prime factors' part of the problem yet. I've just been trying to calculate the prime numbers encapsulated within a given number. So far this is what I have.. and it assumes an input of greater than 1 (since its suppose to be one liner I figure you wouldn't use it to compute a number like one or zero) It prints a list of the prime numbers for now.

#!/usr/bin/perl use strict; use warnings; my $x = 7; # Sample Input my @a; my @p; for (my $i = 2; $i <= $x; $i++) { for (my $z = 2; $z <= $i; $z++) { push @p, $z unless $i % $z; } push @a, pop @p if $#p == 0; @p = (); } print $_, "\n" foreach @a;

I'm going to continue to work on the next section of the problem, but really, do you think this question is a bit much to ask?

Update

Thanks everyone for all of your input and help! I have one final question regarding the example code that moritz was gracious enough to provide (thanks!):

$_ = 1 x shift; while( /^(11+?)\1+$/ ) { print length $1; $_= 1 x ( length() / length $1 ) } print length;

I think I understand the brilliance behind the regular expression, and turning the number into a string, I just have one question about the math. The reg-ex will match the smallest possible factor, right? Each iteration of the loop it effectively divides the length of the string by the match's length. If it does match the smallest possible factor (or exits the loop and prints the length), then how does it ensure that it only picks prime numbers each time?

Update 2

After reviewing the above code and after hearing back from my instructor, here is my non-awesome version of the same code. It assumes numbers greater than 1 are input.

#!/usr/bin/perl use strict; use warnings; my $x = shift; # some number argument for ( my $y = 2; $y <= $x; $y++ ) { next if $x % $y; $x /= $y; print $y, "\n"; redo; }

.. and that in a one-line format looks like

perl -le '$x=shift; for($y=2; $y<=$x; $y++) { next if $x%$y; $x/=$y; p +rint $y; redo }' 7

Thanks everyone!