Simple multiplcation function giving wrong for negative computation

Hi I have written the following program math.ex

defmodule Math do
  def mul(_, 0) do
    0
  end
  def mul(0, _) do
    0
  end

  def mul(a, b) when b < 0 do
    sum = a + mul(a, b+1)
    sum*(-1)
  end

  def mul(a, b) do
    sum = a + mul(a, b-1)
    sum
  end
end

Now, when it try to the do Math.mul(4,-10) the expected answer is the -40 but it gives me 0. Also if i change the line 7 to just return sum instead of sum*(-1) I get 40.

those results very much seem correct! I suggest unrolling your math carefully. Maybe do Math.mul(4, -2) by hand.

mul(a, -1) returns -a, mul(a, -2) returns -(a + mul(a, -1)) which is -(a - a) which is -a + a, which is 0.

So on an even second argument you’ll always get 0 and on odds you get -a.

1 Like