Finding Prime Numbers in a Range

So this was kind of cool. I needed a way to pump out all the prime numbers in a range in order to solve problem #3 in the excellent web zone, projecteuler.net, which I can’t recommend enough. I’m still trying to figure out how to do the prime factorization so any help is appreciated in the comments. This works quite well and returns an array of primes from 1 to whatever you choose. You can of course create a gets.chomp for the lower end of the range.

# Prime numbers within a range

@prime = []

def is_prime(number)
 divisors = []
 (1..number).each { |n| divisors << n if number%n == 0 }
 if divisors.length == 2 || divisors.length == 1
 @prime << number
 end
end

puts "Find all the prime number between 1 and...?"

max_num = gets.chomp.to_i

(1..max_num).each { |n| is_prime(n) } 

p @prime
Finding Prime Numbers in a Range

Leave a comment