Last active
December 16, 2015 11:49
-
-
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).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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