Skip to content

Instantly share code, notes, and snippets.

@komasaru
Created December 15, 2014 05:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save komasaru/8f3c93fe2823c32cbecc to your computer and use it in GitHub Desktop.
Save komasaru/8f3c93fe2823c32cbecc to your computer and use it in GitHub Desktop.
Ruby script to calculate Xth prime number.
#! /usr/local/bin/ruby
# coding: utf-8
# --------------------------------------
# Calculate Xth prime number
# --------------------------------------
class PrimeNumber2
def exec(no)
n, i = 2, 0
loop do
i += 1 if is_prime(n)
break if i == no
n += 1
end
puts "#{i}th PRIME NUMBER: #{n}."
end
private
def is_prime(n)
res = (2..Math.sqrt(n)).any? { |i| n % i == 0 }
return res || n == 1 ? false : true
end
end
PrimeNumber2.new.exec(100000) if __FILE__ == $0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment