Calculate the value of a multiplication using only summation and subtraction operators

Asked

Viewed 144 times

-1

I tried to write a program in which I must calculate the result of a multiplication through sum and subtraction operators only.

I can’t write anything that works, follow the code as close as I got:

var1 = int(input("Digite um numero: "))
var2 = int(input("Digite outro numero: "))
x = 1
y = 0
while x <= var1:
    print (y + var2)
    x = x + 1
    y = var2 + y
  • 2

    Your code, although it has some things to improve, is working perfectly.

3 answers

1

Your code already works (for positive numbers, because if they are negative, you will need an adjustment, explained below). Anyway, we can improve a little...


Basically, multiplication is nothing more than a repeated sum several times. So just do:

var1 = # ler o valor
var2 = # ler o valor

result = 0
for _ in range(var2):
    result += var1

print(result)

Or you can use sum along with a Generator Expression:

result = sum(var1 for _ in range(var2))
print(result)

Which is basically the same thing.

Note that we don’t need the value of the variable in for, so I called her _ (which is a Python convention to indicate that the variable is not used: it is only there to "satisfy the bureaucracy syntax" of the language, which requires having a variable there). But since I am only interested in adding the value of var1 a certain amount of times, whatever the variable of the for.

Of course, there is another way - which should be more inefficient, by creating a list unnecessarily:

result = sum([var1] * var2)

Basically I create a list containing var1, and by multiplying a list by a number, I give another list containing var2 times the contents of the list. In this case, we will have a list with the number var1 repeated var2 times, and just add it all up. Note that I even used multiplication here, but it wasn’t between the numbers ;-)

But as I have already said, this is unnecessarily more inefficient, by generating a random list (and becomes even more inefficient if the numbers are large, because then we will be generating huge lists without need).


There’s only one catch: this method only works if both numbers are positive, or if only var1 is negative. But if var2 is negative, there the range no longer works, so we have to make a small adaptation:

# lê os valores de var1 e var2

if var1 < 0 and var2 < 0: # se ambos forem negativos, inverte o sinal (pois o resultado será positivo)
    var1 = -var1
    var2 = -var2
elif var2 < 0: # se somente var2 for negativo, troca de lugar com var1
    var1, var2 = var2, var1

if var1 > 0 and var1 < var2: # se var1 não é negativo e for menor, também troca com var2
    var1, var2 = var2, var1

# calcula usando um dos métodos acima

If both are negative, just reverse their signal (since the result will be positive).

If only var2 is negative, I change the value of it with var1 (thus, var1 becomes the negative number and var2 the positive).

Another case I change var1 with var2 that’s when var1 is smaller (but only if positive). This is an optimization for the case of var2 be much larger: for example, if var1 for 5 and var2 for 1 million, 1 million iterations will be made to add up the 5. But if I change their values, I will only make 5 iterations adding up to 1 million (of course if both are very large numbers, it won’t make as much difference).

And if you want, you can also include another case, when one of the numbers is zero, because then the result is zero and there is nothing to calculate:

if var1 == 0 or var2 == 0:
    # se um dos números é zero, nem precisa calcular
    result = 0
else:
    # usa o código acima para calcular...

1


is all a matter of mathematical logic itself, what is the logic behind multiplication? you add a number x times, so let’s program:

x = 15
y = 0

for i in range(0, 5):
    y += x

print(y)

the logic is simple, if I want to multiply 15 times 5 for example, I use a for and add in a variable (which is initially 0) my value to be multiplied

if you want you can apply this logic using the same variable to be multiplied

x = 15

for i in range(1, 5):
    x += 15

print(x)

the only difference here is that my for will add 15 on x 4 times, and not 5 as in the first example, this because the variable already starts with 15, it is as if already added the first time

  • an addendum, in this last example, the number to be added, the number you want to multiply, in this case 15, needs to be constant there in for, no matter how much the variable x is set to 15 at the beginning you cannot make the mistake of doing x += x, because after the first "round" do for, x will receive 15 and become 30, and if you are not yet learned, the multiplication operator in python is *, for example x *= 5 would be the equivalent of our progamma.

1

The operation of multiplication is nothing more than successive additions of a certain value. This way the multiplication operation can be mounted as follows:

Multiplying x Multiplier = Product

In this scheme both the multiplicando as to the multiplicador are called factors.

In all multiplication they follow rules of Boolean algebra, the order of its factors do not alter the product.

NOTE: THIS RULE IS ONLY VALID FOR BOOLEAN ALGEBRAS

In this case the rule is valid, since we are using multiplication in the set of integers. Although this is true we must be well aware of what comes to being in fact the multiplying and the multiplier.

  1. Multiplying is any number;
  2. Multiplier is the number of times successive additions will be performed.

Well, let us take the following two examples::

Ex 1:

7 x 3 = 7 + 7 + 7 = 21

Ex 2:

3 x 7 = 3 + 3 + 3 + 3 + 3 + 3 + 3 = 21

In both examples the product will be the same. Only, when we assemble the code should be very clear who will be the multiplying - any number - and who will be the multiplier - the number of iterations of the repeat loop.

Therefore, rearranging his code he will be:

var1 = int(input("Digite um numero: "))
var2 = int(input("Digite outro numero: "))
x = 1
y = 0
while x <= var2:
    y += var1
    x += 1

print(y)

Note that the multiplying will be var1 and the multiplier will be the variable that will be incremented, which in this case will be y. The variable y will be responsible for increasing the successive additions.

Now, if you prefer, you can use an implementation with the repeat loop for. In this case, the code would be as follows::

var1 = int(input("Digite um numero: "))
var2 = int(input("Digite outro numero: "))
y = 0
for x in range(1, var2 + 1):
    y += var1

print(y)

Note that in both codes the multiplying will be the variable var1 and the multiplier will be the variable var2.

Browser other questions tagged

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