1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

エラトステネスの篩で素数を出力するperlスクリプト

Last updated at Posted at 2023-11-26

エラトステネスの篩で素数を出力するperlスクリプトです。
chmod +x sieve.pl
./sieve.pl <n> として実行してください。

sieve.pl
#!/usr/bin/env perl

sub sieve {
  local($n,@tab,@l,$v,$x,@t);
  $n=$_[0];
  @tab=(2..$n);
  @l=();
  while (@tab) {
    $v=shift(@tab);
    push(@l,$v);

    @t=();
    while (@tab) {
        $x=shift(@tab);
        if ( $x % $v ) {
            push(@t,$x);
            }
        }
    @tab=@t;
    }
  return @l;
}

@primes=&sieve($ARGV[0]);
$,=',';
$len=@primes;
print "@primes\nNumber of primes is $len.\n";
1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?