You really should use a smarter algorithm. You are testing a huge amount of numbers that can't possibly matter. JavaFan above has the right idea.

Here's a prime testing function I was noodling around with for comparison. It tests for primality up to 2**32 in about 1/10 sec on my not very fast computer. (Still unrealistically slow for large numbers of tests but ok for the odd single test here and there.)

Updated: fixed error

use warnings; use strict; use Time::HiRes qw/ tv_interval gettimeofday/; my $time0 = [gettimeofday]; # simple routine to test for primality. # don't expect sensible results for numbers above 2**32 # on 32 bit OSs. my $test = shift @ARGV || 2**32 - 5; # number to test my $max = $test**.5; # square root of number to te +st. my @primes; my $isprime; @primes = ( 2, 3 ); #seed the primes array # generate the prime test array. # save it and load it from a file for faster speed. my $this = $primes[-1]; while ( $this < $max ) { $this += 2; my $sqrt = $this**.5; for (@primes) { if ( $_ > $sqrt ) { push @primes, $this if $this < $max; last; } next if $this % $_; last; } } for (@primes) { # test number next if $test % $_; $isprime = 1; } my $elapsed = tv_interval( $time0, [gettimeofday] ); print "$test is ", ( $isprime ? 'not prime.' : 'prime.' ), " In $elapsed seconds.";

In reply to Re: is_a_prime test? by thundergnat
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.