### Re: Calculate prime factors for a given numer in a perl one-liner

by Crackers2 (Parson)
 on Dec 16, 2010 at 02:31 UTC ( #877421=note: print w/replies, xml ) 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.

• Comment on Re: Calculate prime factors for a given numer in a perl one-liner

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!

Create A New User
Node Status?
node history
Node Type: note [id://877421]
help
Chatterbox?
NodeReaper patches his monknet

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (4)
As of 2018-05-26 14:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
World peace can best be achieved by:

Results (194 votes). Check out past polls.

Notices?