Skip to content

Instantly share code, notes, and snippets.

@aoi0308
Created December 25, 2011 05:26
Show Gist options
  • Save aoi0308/1518764 to your computer and use it in GitHub Desktop.
Save aoi0308/1518764 to your computer and use it in GitHub Desktop.
素数をカンマ区切りで各行10個ずつ出力するプログラム。
#!/opt/local/bin/perl
#
# 素数をカンマ区切りで各行10個ずつ出力するプログラム。
#
# 使い方
# $ perl prime.pl {number} [filename]
#
use strict;
use warnings;
use POSIX;
if (@ARGV == 0 or @ARGV > 2) {
print "Usage: ${0} {number} [filename]\n";
exit(0);
}
if (@ARGV == 2) {
open(HNDL, ">${ARGV[1]}");
} else {
open(HNDL, ">-");
}
my @list = &create_prime_list($ARGV[0]);
for (my $i = 0; $i < @list; $i++) {
print HNDL $list[$i];
if (($i + 1) % 10 == 0) {
print HNDL "\n";
} else {
print HNDL ",";
}
}
close(HNDL);
sub create_prime_list($) {
my($length) = @_;
my @list = (2);
my $n = 3;
while (@list < $length) {
push(@list, $n) if &is_prime_number($n, @list);
$n += 2;
}
return @list;
}
sub is_prime_number($@) {
my($n, @ps) = @_;
my $sqrt = floor(sqrt($n));
my @check_list = grep {$_<=$sqrt} @ps;
foreach my $c (@check_list) {
return 0 if ($n % $c == 0);
}
return 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment