How to multiply in Python without the multiplication operator?

8

I have a task and I am having difficulty completing it. What I did was this:

m= int(input('Digite o primeiro fator:'))
n= int(input('Digite o segundo fator:'))

def multiplica(numero):
    while m > 0:
        print (n + multiplica (m-1) n)
def multiplicaneg(numero):
    while m < 0:
        print ((-n) + multiplica (m+1) n)

if m or n == 0:
    print (0)
elif m > 0:
    return multiplica
else:
    return multiplicaneg

What I tried was to create a function to multiply and then, at the time of printing, to return the function with the appropriate result.

    
asked by anonymous 16.05.2018 / 14:59

2 answers

8

This can all be done from a single function and without recursion, using absolute values abs() :

def multiplica(i, j):
  res = 0
  while i > 0:
      res += j
      i -= 1
  return res

i = int(input('Digite o primeiro fator:')) # 11
j = int(input('Digite o segundo fator:')) # -356

res = multiplica(abs(i), abs(j)) # usamos os valores absolutos de ambos, mais tarde verificamos se vai ser negativo ou positivo
if(i < 0 < j or j < 0 < i):
  res = -res

print('{} * {} = {}'.format(i, j, res)) # 11 * -356 = -3916

DEMONSTRATION

If you choose to continue using recursion:

def multiplica(i, j):
  if(j == 0 or i == 0):
    return i
  return i + multiplica(i, j-1)

i = int(input('Digite o primeiro fator:')) # 11
j = int(input('Digite o segundo fator:')) # -356

res = multiplica(abs(i), abs(j)) - i # usamos os valores absolutos de ambos, mais tarde verificamos se vai ser negativo ou positivo
if(i < 0 < j or j < 0 < i):
  res = -res

print('{} * {} = {}'.format(i, j, res)) # 11 * -356 = -3916

DEMONSTRATION

    
16.05.2018 / 15:26
2

Another option is to use the native function sum :

def multiply(a, b):
    result = sum(b for _ in range(abs(a)))
    return result if a > 0 else -result

See working at Repl.it | Ideone | GitHub GIST

In which the value of b will be added a quantity equal to the absolute value of a , independent of the b sign, since adding negative numbers results in a negative number. The only question is whether to reverse the result signal according to the a sign. If positive, hold the signal, but if negative, it reverses.

So:

print(multiply(2, 5))   # 10
print(multiply(-2, -5)) # 10

print(multiply(-2, 5))  # -10
print(multiply(2, -5))  # -10
    
16.05.2018 / 20:16