Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

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

by Crackers2 (Vicar)
on Dec 16, 2010 at 02:31 UTC ( #877421=note: print w/ replies, xml ) Need Help??


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.


Comment on Re: Calculate prime factors for a given numer in a perl one-liner
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!

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://877421]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (5)
As of 2014-09-21 12:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (168 votes), past polls