Here's a nice version for if you need to check a lot of large numbers to see if they're prime:
use strict;
use warnings;
my ($c, $i) = 0;
for ($i = 36544645654; $c < 100; $i++) {
$c++, print "$i\n" if prime($i);
}
BEGIN {
my @primes = (2);
sub prime {
my $n = $_[0]; my $p;
my $rt = int sqrt $n;
for $p (@primes) {
return 0 if $n % $p == 0;
return 1 if $p >= $rt;
}
for $p (($primes[-1]+1)..$rt) {
if (prime($p)) {
push @primes, $p;
return 0 if $n % $p == 0;
}
}
return 1;
}
}
This version remembers the primes you've found so far, and only checks necessary numbers to see if they're prime. Yes, I know you could also start by knocking out all the /2, /3, /5, etc numbers in your range, but this doesn't improve speed very much, and adds complexity to your code.
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.