Tiantian Shi
Tiantian Shi

Reputation: 21

Determing whether number is prime in Ruby

I'm trying to write a method that returns true or false based on whether the integer being evaluated is prime or not. The below code is something I've cobbled together based on reading Wikipedia articles, previous stackoverflow answers, etc. Currently the program returns true for prime numbers, but doesn't return false. I want to do this without using any built-in functions. How should I fix this?

def prime?(integer)
 (2..integer - 1).each do |x|
  if (integer % x) == 0
   return false
  else
   return true
  end
end
end

Upvotes: 0

Views: 1504

Answers (2)

gonzalo2000
gonzalo2000

Reputation: 648

An alternative, starting out with a variable set to true.

def prime?(integer)
  (2..integer - 1).each {|x| return false if (integer % x) == 0 }
  true
end

Upvotes: 1

T. Claverie
T. Claverie

Reputation: 12256

You've got a logic problem. The program returns true for any number that's not divisible by 2. So, just put the return true statement after the loop has been executed completely.

def prime?(integer)
    return false if integer < 2
    (2..integer - 1).each do |x|
        if (integer % x) == 0
            return false
        end
    end
    true
end

Upvotes: 1

Related Questions