|Syntactic Confectionery Delight|
Re: Calculate prime factors for a given numer in a perl one-linerby Crackers2 (Parson)
|on Dec 16, 2010 at 02:31 UTC||Need Help??|
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?
Think it through for a minute. Let's start at 2, the first prime; it'll keep finding matches until it's no longer divisible.
Next number is 3; same thing, keep going until it's no longer divisible.
Next _possible_ number is 4... but if 4 would work, then 2 would have worked as well. So it's not going to find any matches.
Next number is 5, prime. Nothing special
Next one, 6... anything that works for 6 would also have worked for 2 and 3, so again it won't find anything.
And you can keep going. There won't be any matches of a non-prime number length, since those would have always been matched by one of the (smaller) prime factors of that number. You might want to look at the Sieve of Eratosthenes to see why this works.