How do I generate the first n prime numbers?

Viewed 33669

I am learning Ruby and doing some math stuff. One of the things I want to do is generate prime numbers.

I want to generate the first ten prime numbers and the first ten only. I have no problem testing a number to see if it is a prime number or not, but was wondering what the best way is to do generate these numbers?

I am using the following method to determine if the number is prime:

class Integer < Numeric
  def is_prime?
    return false if self <= 1
    2.upto(Math.sqrt(self).to_i) do |x|
      return false if self%x == 0
    end
    true
  end
end
15 Answers

Implemented the Sieve of Eratosthene (more or less)

def primes(size)
    arr=(0..size).to_a
    arr[0]=nil
    arr[1]=nil
    max=size
    (size/2+1).times do |n|
        if(arr[n]!=nil) then
            cnt=2*n
            while cnt <= max do
                arr[cnt]=nil
                cnt+=n
            end
        end
    end
    arr.compact!
end

Moreover here is a one-liner I like a lot

def primes_c a
    p=[];(2..a).each{|n| p.any?{|l|n%l==0}?nil:p.push(n)};p
end

Of course those will find the primes in the first n numbers, not the first n primes, but I think an adaptation won't require much effort.

I did this for a coding kata and used the Sieve of Eratosthenes.

puts "Up to which number should I look for prime numbers?"
number = $stdin.gets.chomp
n = number.to_i
array = (1..n).to_a

  i = 0

while array[i]**2 < n

i = i + 1
array = array.select do |element|
  element % array[i] != 0 || element / array[i] == 1


end
end

 puts array.drop(1)

Here's a super compact method that generates an array of primes with a single line of code.

  def get_prime(up_to)
    (2..up_to).select { |num| (2...num).all? { |div| (num % div).positive? } }
  end
Related