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


in reply to Calculate prime factors for a given numer in a perl one-liner

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.

Replies are listed 'Best First'.
Re^2: Calculate prime factors for a given numer in a perl one-liner
by andmott (Acolyte) on Dec 16, 2010 at 02:54 UTC
    Thanks I appreciate it!