Jorge Lopez Jr
Jorge Lopez Jr

Reputation: 257

Project Euler #6 in Ruby (What's the difference?)

I solved #6 for Project Euler using two different methods, but the second one just happened to be coincidental. I don't really understand why I don't have to return the square of new_sum like I did for my first method. Does anyone know what's the major difference between the two?

def square_difference(num)
  new_sum = 0
  sum = 0
  while num >= 1
    sum += num**2 && new_sum += num
    num -= 1
  end
  return new_sum**2 - sum
end

AND

def square_difference(num)
  new_sum = 0
  sum = 0
  while num >= 1
    new_sum += num && sum += num**2  
    num -= 1
  end
  return new_sum - sum
end

Upvotes: 0

Views: 96

Answers (2)

fylooi
fylooi

Reputation: 3870

Both formulas have the same subtle bug. I stepped through it a couple of times to understand what was going on.

From the second one:

[30] pry(main)> square_difference(4)
new_sum: 16, sum: 16, num: 3
new_sum: 41, sum: 25, num: 2
new_sum: 70, sum: 29, num: 1
new_sum: 100, sum: 30, num: 0
=> 70

We can see that new_sum does not seem to be behaving as intended.

What is actually happening is that new_sum += num && sum += num**2 is being evaluated to new_sum += (num && sum += num **2), which in turn evaluates to new_sum += (sum += num **2)

This is a result of the && operator, which has higher precedence (as Yu Hao pointed out) and returns the first value which determines whether the AND condition is satisfied.

[31] pry(main)> 2 && 2
=> 2
[32] pry(main)> 2 && 4
=> 4
[33] pry(main)> 4 && 2
=> 2
[34] pry(main)> nil && 2
=> nil
[35] pry(main)> 2 && nil
=> nil

Upvotes: 1

Yu Hao
Yu Hao

Reputation: 122383

The precedence of && is higher than that of +=. So these expressions:

sum += num**2 && new_sum += num

new_sum += num && sum += num**2 

don't work as you expected. The first one just happen to provide the seemingly "correct" result.

Divide them into separate lines and you'll see the difference. Or, at least use and instead of &&. and has a lower precedence than that of +=.

Upvotes: 2

Related Questions