|Welcome to the Monastery|
Calculate prime factors for a given numer in a perl one-linerby andmott (Acolyte)
|on Dec 15, 2010 at 17:11 UTC||Need Help??|
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.
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?
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!):
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?
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.
.. and that in a one-line format looks like