Search code examples
algorithmmultiplicationaddition

algorithm to simulate multiplication by addition


How to design an algorithm to simulate multiplication by addition. input two integers. they may be zero, positive or negative..


Solution

  • def multiply(a, b):                                                                                                                                                               
        if (a == 1):
            return b
        elif (a == 0):
            return 0
        elif (a < 0):
            return -multiply(-a, b)
        else:
            return b + multiply(a - 1, b)