Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a method that returns the nth prime number?

Tags:

ruby

primes

I'm trying to write a method that returns the nth prime number.

I've worked out a solution but the problem is in my method. I create a large array of numbers that seems to process super slow. (1..104729).to_a to be exact. I chose 104729 because the max n can be is 10000 and the 10000th integer is 104729. I'm looking for a way to optimize my method.

Is 104729 is too large a value? Is there a way to write this so that I'm not creating a large array?

Here's the method:

def PrimeMover(num)

  def is_prime(x)
    i = 0
    nums = (2..x).to_a
    while nums[i] < nums.max
      if x % nums[i] != 0
        i += 1
      else
        return false
      end
    end
    return true
  end

  primes_arr = (3..104729).to_a.select {|y| is_prime(y)}

  primes_arr[num]

end
like image 383
user3640511 Avatar asked Dec 02 '22 18:12

user3640511


2 Answers

require "prime"

def find_prime(nth)
  Prime.take(nth).last
end
like image 168
Arturo Herrero Avatar answered Jan 17 '23 22:01

Arturo Herrero


Combine Ruby's built-in prime library, and a lazy enumerator for performance:

require 'prime'
(1...100_000).lazy.select(&:prime?).take(100).to_a

Or simply, as highlighted by Arturo:

Prime.take(100)
like image 28
Denis de Bernardy Avatar answered Jan 17 '23 22:01

Denis de Bernardy