tags:

views:

80

answers:

2

I'm running through the problems on Project Euler to teach myself Ruby programming. I know there is a built-in function to do this, but I'm avoiding the built-in functions to help me learn.

So I have to write a method to determine if a number is a prime. The first method works, but the second doesn't. Can anyone explain why?

 def is_prime n
  for d in 2..(n - 1)
   if (n % d) == 0
    return false
   end
  end

  true
 end

 def is_prime2 n
  foundDivider = false
   for d in 2..(n - 1)
    foundDivider = ((n % d) == 0) or foundDivider
   end
  not foundDivider
 end
+5  A: 

It's because = is of higher precedence than or (see Ruby's operator precedence table).

The problematic line is being parsed as...

(foundDivider = ((n % d) == 0)) or foundDivider

...which is certainly not what you mean. There are two possible solutions:

Force the precedence to be what you really mean...

foundDivider = (((n % d) == 0) or foundDivider)

...or use the || operator instead, which has higher precedence than =:

foundDivider = ((n % d) == 0) || foundDivider
Chris Schmich
This is why I love StackOverflow. Thanks a million
Jaco Pretorius
A: 

Nice. I found the question, and the answer useful! I too am running through Project Euler to learn Ruby.

One performance improvement suggestion I have is to change the range from 2..(n-1) to 2..(Math.sqrt(n)); reduces the number of iterations significantly.

Prakash Murthy
Good point, thanks
Jaco Pretorius