Skip to content

Instantly share code, notes, and snippets.

@kamipo
Created April 30, 2010 09:32
Show Gist options
  • Save kamipo/384997 to your computer and use it in GitHub Desktop.
Save kamipo/384997 to your computer and use it in GitHub Desktop.
素数を求める(新卒のときの課題)
#!/usr/bin/perl -l
use strict;
use Time::HiRes;
my $start_time = Time::HiRes::time;
main(int($ARGV[0]) || 10_000);
my $end_time = Time::HiRes::time;
my $computation_time = $end_time - $start_time;
print $computation_time;
sub main {
my $max = shift;
my $sqrt_max = int sqrt $max;
my @not_prime;
my $prime = '2';
for my $n ( 3 .. $sqrt_max ) {
(!($n & 0x01) or $not_prime[$n >> 1]) and next;
$prime .= ",$n";
for (my ($i, $d) = ($n ** 2, $n * 2); $i <= $max; $i += $d) {
$not_prime[$i >> 1] = 1;
}
}
for my $n ( $sqrt_max + 1 .. $max ) {
(!($n & 0x01) or $not_prime[$n >> 1]) or $prime .= ",$n";
}
print $prime;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment