Created
December 15, 2014 05:06
-
-
Save komasaru/8f3c93fe2823c32cbecc to your computer and use it in GitHub Desktop.
Ruby script to calculate Xth prime number.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /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