Translate

Image of Linux Kernel Development (3rd Edition)
Image of Operating System Concepts
Image of Advanced Programming in the UNIX Environment, Second Edition (Addison-Wesley Professional Computing Series)
Image of Modern Operating Systems (3rd Edition)

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:

#!/usr/bin/perl

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.