Image of Android Wireless Application Development
Image of RHCE Red Hat Certified Engineer Linux Study Guide (Exam RH302) (Certification Press)
Image of Linux Kernel Development (3rd Edition)
Image of Beginning Google Maps API 3

Calculating Prime Numbers using Perl

Definition of a prime number:

  • A prime number is defined by any number that is only dividable by 1 or itself.
  • Except for 2 which is a prime, a prime number is always odd (2n+1)

Here is a Perl script which outputs all the prime numbers between 0 and 10000:


my $UPPER = 10000;

my $sieve = "";
print "2n";
for (my $guess = 3; $guess < = $UPPER; $guess+=2) {
    next if vec($sieve,$guess,1);
    print "$guessn";
    for (my $mults = $guess * $guess; $mults <= $UPPER; $mults += $guess)
       vec($sieve, $mults, 1) = 1;

Comments are closed.