LoginSignup
4
4

More than 5 years have passed since last update.

ある整数にもっとも近い素数を求める

Last updated at Posted at 2014-01-06

ご祝儀の金額を素数にして割り切れなくするという洒落たことをした記事を見かけて触発された。

こちらにEnumerable#each_consとEnumerable#lazyを使ってそれっぽく書き直したものを投稿しました。

require 'prime'

class Prime
  def nearest_prime? (n)
    d = 0
    loop do
      p = n + d
      break p if Prime.prime? p
      p = n - d
      break p if Prime.prime? p
      d += 1
    end
  end
end

Prime.nearest_prime? 30000
=> 30011
Prime.nearest_prime? 50000
=> 49999

んーrubyぽくない

4
4
0

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
4
4