Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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..

like image 994
KawaiKx Avatar asked Aug 28 '26 04:08

KawaiKx


2 Answers

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)
like image 197
Dr. Acula Avatar answered Aug 30 '26 19:08

Dr. Acula


some pseudocode:

function multiply(x, y)
  if abs(x) = x and abs(y) = y or abs(x) <> x and abs(y) <> y then sign = 'plus'
  if abs(x) = x and abs(y) <> y or abs(x) <> x and abs(y) = y then sign = 'minus'

 res = 0
 for i = 0 to abs(y)
  res = res + abs(x)
 end

 if sign = 'plus' return res
    else return -1 * res

end function
like image 38
Tudor Constantin Avatar answered Aug 30 '26 17:08

Tudor Constantin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!