How to multiply in Python without the multiplication operator?

Asked

Viewed 4,581 times

12

I have a task and I’m having trouble 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, when printing, return the function with the proper result.

  • Very good your code, but I could not understand it. Could you explain to me what is happening in the code? Because I wanted to make the code myself, you know? Understand the idea and create my own :/

4 answers

12


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

  • "res += j" ? I’ve never seen this syntax, which means?

  • We’re incrementing in the variable itself to which we’re assigning the value, it’s the same as res = res + j, in this case is by facilitism (write less)

  • Thank you very much, I think I’m beginning to understand the code. Last question: can I take something from my code? :/

  • @Paulajaquelinesva by my mistake I forgot to cover the chance of both being negative (gives positive), but is corrected, dsculpa. In the case of this reply I was able to take advantage int(input('Digite o primeiro fator:')), the while and almost the name of the d: function, and the variable names you can put as you want

3

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 on Repl.it | Ideone | Github GIST

In which the value of b an amount equal to the absolute value of a, independent of the signal from b, because adding negative numbers results in a negative number. The only question is whether to reverse the result signal according to the a. If positive, keep the signal, but if negative, reverse.

Thus:

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

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

0

This question brings to light the very definition of multiplicação.

What is multiplication?

Multiplication is nothing more than soma of parcelas iguais.

Example 1: How much 2 x 4?

 (2 * 4) == 4 + 4 == 8

This means that 2 x 4 is the summing up of 2 plots of 4.

Example 2: how much is 3 x 9?

(3 * 9) == 9 + 9 + 9 == 27

This means that 3 x 9 is the summing up of 3 plots of 9.

If we accept the condition that multiplicação in the set of real numbers is comutativa, we can say that:

(2 * 4) == (4 * 2) == 2 + 2 + 2 + 2 == 8

That is to say, 4 x 2 is the soma of 4 plots of 2 and...

(3 * 9) == (9 * 3) == 3 + 3 + 3 + 3 + 3 + 3 + 3 + 3 + 3 == 27

That is to say, 9 x 3 is the soma of 9 plots of 3.

Now, with this explanation it becomes much easier to implement a laço de repetição to calculate the product between two fatores without using the operador of multiplicação.

If you want to use the loop for to resolve this issue, you can use the following algorithm...

f1 = int(input('Digite o primeiro fator: '))
f2 = int(input('Digite o segundo fator: '))

soma = 0
for c in range(f1, f2 + f1):
    soma += f1
print(f'\033[32mO produto é: {soma}')

Note the functioning of the algorithm in repl it.

Note that f1 is the first factor and f2 is the second factor.

-1

I have an answer in that form, but it only works for natural numbers.

n1=int(input("Fator:"))
n2=int(input("Fator:"))
x=1
soma=n1
while x<n2:
    soma=soma+n1
    x=x+1
print(f"Resultado: {soma}")
  • It doesn’t really work in case n2 be zero because the answer should be zero and will always be n1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.