Tuesday, March 1, 2011

Prime Number in Perl with a twist

Just a few days ago, I learned that all prime numbers > 3 can be represented as multiple of 6 +1 or -1.

So here's a code in perl to find nth prime number.


#!/usr/bin/perl

print "Enter the number: ";
chomp($num = <>);
$i = 3;
$no_of_prime = 3;
$prime = 0;
if ($num == 1)
{
print "1st prime is 2 \n";
}
elsif ($num == 2)
{
print "2nd prime is 3 \n";
}
elsif ($num > 2)
{
$index = 1;
$powindex = 1;
$no_of_prime = 2;
while($no_of_prime < $num)
{
$prime = (6 * $index) + ((-1) ** $powindex);
$j = 2;
$is_prime = 1;
while($j <= ($prime ** 0.5))
{
if(($prime % $j) == 0)
{
$is_prime = 0;
break;
}
$j = $j + 1;
}

if ($is_prime == 1)
{
$no_of_prime++;
}

if(($powindex % 2) == 0)
{
$index = $index + 1;
}

$powindex = $powindex + 1;
}
print $num, "th prime is: ", $prime, "\n";
}
else
{
print "Invalid number\n";
}
#END