Image of RHCE Red Hat Certified Engineer Linux Study Guide (Exam RH302) (Certification Press)
Image of XSLT 2.0 and XPath 2.0 Programmer's Reference (Programmer to Programmer)
Image of Advanced Programming in the UNIX Environment, Second Edition (Addison-Wesley Professional Computing Series)
Image of Android Wireless Application Development

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.