def prime?(num)
return false if num == 1
(2..num/2).each do |x|
if num%x==0
return false
end
end
true
end
Asked
Active
Viewed 49 times
1

Sergio Tulentsev
- 226,338
- 43
- 373
- 367

John Morris
- 11
- 1
-
1For what it's worth, you can shorten this brute force attempt a bit by going up to the *square root* of `num`, not the half. – vcsjones Jun 09 '17 at 19:58
3 Answers
2
Because you never enter your each
. If the value is 2, then (2..num/2)
becomes (2..2/2)
, which is (2..1)
. Ruby's range operators don't go backwards, so there is nothing to "each" over.

vcsjones
- 138,677
- 31
- 291
- 286
-
1The good news is that 2 _is_ a prime number so returning `true` is not a problem :) – whodini9 Jun 09 '17 at 19:56
0
I believe that since (num/2) is 1 in that case, the loop never runs, so it falls through to the 'true' at the bottom.

PMar
- 1
0
I think your method is working:
puts prime?(2)
#=> true
As someone mentioned in the comments, you can also save some steps by only going through the sqrt
of the number:
(2..Math.sqrt(num)).each do |x|

Kathryn
- 1,557
- 8
- 12