multiplication algorithm per soma

1

I'm doing a job that I need to create an algorithm that turns product into sum or difference and I can only use the + , - , and else , if , print and% with%. I was able to do multiplication of positive numbers, but I can not optimize (Ex: while is not optimized, input is optimized) and hit the signal in multiplication of numbers, negative with negative and positive with negative 4x2= 2+2+2+2 , something that is wrong).

Here are the lines of code I was able to do:

N1 = int(input('Digite um número'))
N2= int(input('Digite um número'))

if ((N1==0) or (N2==0)):
    print('0')
else:
    if (N1<0) != (N2<0):
     N1
    if N1<0:
     N1 =-N1
    if N1<0:
     N2=-N2
    if N1>N2:
        maior=N1
        menor=N2
    else:
        maior=N2
        menor=N1

    result=0
    Count=0

    if (menor>0):
        while (Count<menor):
            result=result+maior
            Count=Count+1
    else:
        while (Count>menor):
            result=result-maior
            Count=Count-1
    print(result)
    print(Count)
    
asked by anonymous 10.05.2018 / 19:58

1 answer

0

I managed to break my mind here and I think that I solved the problem and optimized the code a bit.

N1 = int(input('Digite um número'))
print()
N2 = int(input('Digite um número'))
print()

if ((N1==0) or (N2==0)):
    print('0')
else:
    maior, menor = [N1,N2] if N1 >= N2 else [N2,N1]

    result=0
    Count=0

    # print('menor = {} e maior = {}'.format(menor, maior)) # Puramente debug

    if (menor>0):
        while (Count<menor):
            result=result+maior
            Count = Count + 1
    else:
        while (Count>menor):
            result=result-maior
            Count = Count - 1
        Count = -Count
    print('Resultado = {}'.format(result))
    print('Repetições = {}'.format(Count))

functional link in ideone

What I've changed:

  • Simplified initialization: it is totally unnecessary to check if both numbers are negative and convert each one to positive.
  • I removed the sign changes from the numbers: This was causing almost every bugs in the program.
  • Third IF within ELSE will never run if you continue with the same test because N1 was negative and was converted to positive so it would fail in the same test
  • 10.05.2018 / 21:48