...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.

In reply to Re^3: is_a_prime test? by sierpinski
in thread is_a_prime test? by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.