Need help on a prime? method problem:
my code keeps returning true for 27 being a prime number…can someone tell me what’s wrong with my code?
Thank you! And I looked up someone else’s answer, i don’t know why he sets the range to (2…num/2)
black one is mine and gives error, the white one is correct.
Please someone helps me…being stuck for an hour.
my code: def prime?(num)
if num == 1
elsif num == 2
arr = (3…num-1)
arr.each do |n|
if num%n == 0
Someone else’s correct code:
return false if num == 1
(2…num/2).each do |x|
The issue I see with your code is the part where you are return true. You are returning true if num%n does not equal 0. That means the very first time an n does not equal 0, you’ll return true. Instead what I think you want to do is return true at the very end like in the example of correct code you showed. The reason for this being that you want to go through all the values for n and and check that none of them divide equally.
The second part of your question about why you can use the range (2…num/2) is because you know that any number over num/2 will not divide evenly into num. This is because the greatest number that can evenly divide into a number is num/2. The numbers after that are too big.
Let me know if you have any other questions!