Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

Daniel Wise
Daniel Wise
9,119 Points

Having trouble returning a true/false boolean value

I am trying to get this method to return a boolean value of true for prime numbers and false for when a number is not prime. So far it is returning true but not false. Here is the code I have created so far.

def prime?(num=1..11)
    array = (1..11).to_a
if num > 1 
    return true 
elsif num / 2 || 3 
    return false 
    end 
end 

My logic behind this was that the prime? method would take in a range as an argument and that argument I would set to an array (I have to set it equal to an array in this instance its part of the exercise). Since prime numbers are greater than 1 and divisible by their selves I set it to return true if the range is greater than 1. Since the numbers between 1-11 can be divisible by 2 or 3, I made the method return false if any number is divisible by 2 or 3. I feel I made some error in this code but this is what I am trying to achieve. Thanks for any help!

1 Answer

samuel gustave
samuel gustave
7,341 Points

Hi ! if you're trying to determine if a number n is prime, why would you pass a range as argument to method prime?() 0 and 1 are not prime (prime number have only two divisers: 1 and themselves) I suggest you this :

def prime?(n)
   if n % 2 == 0 || n % 3 == 0 # if n modulo 2 = 0 or n modulo 3 = 0, n cannot be prime
      return false # not prime
    else
       return true
    end
end

There are 4 particular cases that needs to be adressed : 0 and 1 are not prime 2 and 3 are prime