5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

1行で素数列挙

Posted at

はじめに

ふと思いつきで1行で素数を求めるプログラムを書いてみました。効率ではなくコード量重視。

Ruby

filter かと思ったら Range の場合 select なんですね。(Ruby 2.5)

(2..99).select {|x| (2...x).select {|i| x % i == 0} == []}

Python

filter でもいいけれどリスト内包表記の方がすっきり書けます。

[x for x in range(2, 100) if [i for i in range(2, x) if x % i == 0] == []]

Haskell

Haskell は何年たっても勉強中の初心者から抜け出せません。

[x | x <- [2..100], [i | i <- [2..(x - 1)], mod x i == 0] == []]

まとめ

リスト内包表記ができないRubyが不利かと思ったら、意外なことにぼくが書いた中では一番短かった。

5
1
6

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
5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?