3
2

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.

Ruby 素数を求めるアルゴリズム

Last updated at Posted at 2020-04-16
def prime(n)
  num = 2
  catch(:break_loop) do  
    while n > num do
      if (n % num) == 0 
        # puts "#{n} is not prime number"
        throw :break_loop
      end      
      num += 1
    end
      puts "#{n} is prime number"
  end
end

2.step do |i|
  prime(i)
  # break if i == 100
end

↑これをコピペして実行してください!

素数を求める永遠の旅に出れます

もし、素数でない数字も一緒に表示したい場合こちらをコピペして実行してください↓(コメントアウト外しただけです)

def prime(n)
  num = 2
  catch(:break_loop) do  
    while n > num do
      if (n % num) == 0 
        puts "#{n} is not prime number"
        throw :break_loop
      end      
      num += 1
    end
      puts "#{n} is prime number"
  end
end

2.step do |i|
  prime(i)
  # break if i == 100
end

※注意
このまま実行すると無限に素数を求め続け、処理が終わりません。
もし、任意の数字で処理を止めたい場合、breakの前についてる#を取ってコメントアウトしてから、100と書かれている部分を任意の数字に置き換えてください!

2.step do |i|
  prime(i)
  break if i == 100
end
3
2
2

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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?