Skip to content

Instantly share code, notes, and snippets.

@binary132
Last active December 16, 2015 11:49
Show Gist options
  • Save binary132/5430277 to your computer and use it in GitHub Desktop.
Save binary132/5430277 to your computer and use it in GitHub Desktop.
Seive of Aritosthenes in Perl (print to STDOUT all prime numbers less than or equal to N, in argument -pN).
#!/usr/bin/perl
use Getopt::Std;
use vars '$opt_p';
use strict;
use warnings;
getopts('p:');
# create a list of numbers from 2 to n
# numbers which are not prime will be "marked" with a 0
my %all_numbers = map { $_ => 1 } (2 .. $opt_p);
# all composite numbers <= $opt_p will have one factor <= sqrt( $opt_p )
for my $factor (2 .. sqrt( $opt_p )) {
# mark all values n that are products of $factor, n <= $opt_p
# so, if value not already marked, make a map of its products
# up to $factor * int($opt_p/$factor)
# e.g. 100/9 = 11.111.. -> 9*11 = 99 <= 100 < 108 = 9*12
if($all_numbers{$factor})
{
$all_numbers{$_} = 0
for map { $factor * $_ } ( $factor .. int($opt_p/$factor) );
}
}
# all_numbers that are not marked false are primes
{
local $, = ' ';
print sort { $a <=> $b } grep { $all_numbers{$_} } keys %all_numbers;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment