Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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