find the nth prime number in ruby

To find the nth prime number in Ruby, we can use a combination of loops, conditionals, and recursion. Here's one way to do it:

main.rb
require 'prime'

def find_nth_prime(n)
  Prime.first(n).last
end

66 chars
7 lines

In this code, we are using the Prime module in Ruby, which provides methods to work with prime numbers. Specifically, we are using the first method to generate the first n primes, and then using the last method to get the nth prime number.

Here's an example of how to use this method:

main.rb
p find_nth_prime(10) #=> 29
28 chars
2 lines

This will print out the 10th prime number, which is 29.

Another way to find the nth prime number is using a while loop and checking each number until we find the nth prime:

main.rb
def find_nth_prime(n)
  primes = [2]
  num = 3
  while primes.length < n
    primes << num if is_prime(num, primes)
    num += 2
  end
  primes.last
end

def is_prime(num, primes)
  primes.each do |prime|
    return false if num % prime == 0
    break if prime * prime > num
  end
  true
end
292 chars
18 lines

In this code, we start with an array containing the first prime number, 2, and then we check each odd number starting from 3 until we find the nth prime. We check whether each number is prime using the is_prime method, which checks whether the number is divisible by any of the primes we have found so far.

Here's an example of how to use this method:

main.rb
p find_nth_prime(10) #=> 29
28 chars
2 lines

This will print out the 10th prime number, which is 29.

gistlibby LogSnag