I need to write the function mult( n, m ) that should output the product of the two integers n and m. I am limited to using addition/subtraction/negation operators, along with recursion.
This is what I have so far:
def mult( n, m ):
if m == 0:
return 0
elif m < 0:
return n - n(m+1)
else:
return n + n(m-1)
Can someone help me please because I can't figure it out!
You are trying to call n(m+1)
in your elif
and else
block, since you say n
is an integer, this is the problem, you should be calling mult()
function recursively sending n
and m+1
or m-1
as parameters.
Another issue is that you should convert the result of n - mult(n, m+1)
to negative before returning.
Example -
...
return - (n - mult(n, m+1))
else:
return n + mult(n, m-1)
Demo with example changes -
>>> mult(5,-3)
-15
>>> mult(-10,-3)
30
>>> mult(5,3)
15