Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiplication function with recursion in Python

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!

like image 919
Benjamin Brooks Avatar asked Jul 10 '26 21:07

Benjamin Brooks


2 Answers

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
like image 101
Anand S Kumar Avatar answered Jul 13 '26 13:07

Anand S Kumar


Multiplication with Recursion in Python:

def multiplication(num_a, num_b):
   if num_a == 0 or num_b == 0:
     return 0
   return num_a + multiplication(num_a, num_b - 1)
like image 29
Vishal7017 Avatar answered Jul 13 '26 11:07

Vishal7017