Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re^3: is_a_prime test?

by sierpinski (Chaplain)
on Oct 25, 2010 at 13:02 UTC ( [id://867216]=note: print w/replies, xml ) Need Help??


in reply to Re^2: is_a_prime test?
in thread is_a_prime test?

...and really you only have to check other primes (they're all odd numbers) after 2, which I suppose you could generate over time in an array, at least to some orders of magnitude, so that subsequent calls to said routine were further optimized...

That's what I was going to suggest. If you created an is_even function, you could rule out (on average) half of your iterations by ruling out the even numbers first. Of course that would require a special case where n=2, but that would be a single-liner.

Even as optimized as you can be, throwing it really large numbers will always take a very long time, so to give the user some kind of indication that your program is not hung, consider putting in some type of progress indicator. Since you know what the number is, you'd know about how many factors you'd have to check (is it 1 to n, or something else that's fixed?) so you could add something like this:
# Used for progress indicator select STDERR; $| = 1; ... # Progress indicator, final value $progress = ($count / $total_count) * 100; printf "Progress: %4.1f\%\r",$progress; # Set carriage returns back to normal after progress indicator is comp +lete select STDOUT; print "\n"; $| = 0;
This works really well for a script I use that connects to several hundred servers. Of course it's only useful when you're executing it from a shell, as opposed to cron or some other background process.

Hope that helps.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (2)
As of 2024-04-25 19:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found