Translate

Archives

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.