Martin
Martin

Reputation: 85

The code below is supposed to return the least perfect square that when added to it, the sum is also a perfect square

So suppose I give 13 as n, the code should return 36 because 36 is the least perfect square that when added to 13 it gives 49 which is a perfect square. Now when I give 4 as n, it should return -1 because 4 added to all the numbers has no perfect square hence it's returning nothing. The code works without adding the elsif but that means if I pass in 4 it will return the range. But once I add the elsif it still prints out the range.

def solve n
    arr = (1..10).each do |i|
    i = (i**2) + n
    if (Math.sqrt(i) % 1) == 0 
          return i - n
    elsif false
          return -1
    end
    
  end  
  arr
end



p solve(13) #= 36
# # because 36 is the smallest perfect square that can be added to 13 to form a perfect square => 13 + 36 = 49

p solve(3) #= 1 # 3 + 1 = 4, a perfect square
p solve(12) #= 4 # 12 + 4 = 16, a perfect square
p solve(9) #= 16 
p solve(4) #= -1

Upvotes: 3

Views: 60

Answers (1)

Sebastián Palma
Sebastián Palma

Reputation: 33420

The thing is your code is never entering to the elsif branch, that's why you're getting the (1..10) range after the iteration because that's the value arr holds and as there's no return value after checking if (Math.sqrt(i) % 1) == 0.

You could just return -1 if there was no a explicit return during the iteration:

def solve n
  (1..10).each do |i|
    i = (i**2) + n
    return i - n if (Math.sqrt(i) % 1).zero?
  end
  -1
end

solve(3)  # 1
solve(12) # 4
solve(9)  # 16
solve(4)  # -1

Upvotes: 1

Related Questions