0

I have an exercise in which I have to create a method that returns true for prime numbers and false for non-prime numbers without the use of math operators.

def prime?(number)
  (2..number/2).none? {|n| return false if number <= 1 || number % n == 0}
end
lurker
  • 56,987
  • 9
  • 69
  • 103
Eric Hill
  • 1
  • 1
  • 1
  • What's your question? Is there a problem with the method you wrote? Outside of `prime?(1)` returning `true`, I think it does what you're wanting it to do. – lurker Mar 22 '16 at 01:49
  • Hello lurker thanks for you response. this code returns a true value for prime numbers, but it doesn't return a false value for non prime numbers – Eric Hill Mar 22 '16 at 02:00
  • 1
    Yes it does. At least it does when I run it. For example, if I call `prime?(6)` it returns `false`. – lurker Mar 22 '16 at 02:02
  • 1
    `number >= 2 && (2..number/2).none? { |n| number % n == 0 }` is faster and makes more sense; but I can't find that your answer is in any way wrong. Also, smartass answer: `require 'prime'; def prime?(n); Prime.prime?(n); end` uses no math operators :P – Amadan Mar 22 '16 at 02:04
  • I think something may be wrong with the test provided to me by the school – Eric Hill Mar 22 '16 at 02:06
  • I just ran this code in irb and everything checks out. thanks lurker. – Eric Hill Mar 22 '16 at 02:07
  • @EricHill in OP you stated `without the use of math operators` and you are using `/,||,<=,||,%,==` those all are math operators (arithmetic and logic). Without any use of them you need to use assembler ... or you have specified which operators not to use? Also look here [Prime numbers by Eratosthenes quicker sequential than concurrently?](http://stackoverflow.com/a/22477240/2521214) for some speedup ideas – Spektre Mar 22 '16 at 08:25

0 Answers0