How do you multiply using while without using multiplication? [closed]

 ̄綄美尐妖づ 提交于 2020-08-03 11:34:08

问题


I want to know how to get the product of two integers using only the addition or subtraction operators and without using the division and multiplication. If you could add the while statement that would be helpful. A

Basically, I want to know how to add a certain number a certain number of times as defined by the user. Adding number x to itself y number of times. To have the user define the number of times to loop this, use int (). Thanks and please use comments where necessary. I am still a bit new to this and thank you.

Here is my current code:

# Asks user for two numbers to multiply
print ('Give me two numbers to multiply.')
print ()
# Gets input from the user
x = int ( input ('First Number: '))
y = int ( input ('Second Number: '))
z = 0
# Does the "multipling"
while z <= x*y:
    print (z)
    z = z + x
    time.sleep(.2)

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Thanks for the help... i figured it out though

import time

print ('Two Digit Multiplication Calculator') print ('===================================') print () print ('Give me two numbers.')

x = int ( input (':'))

y = int ( input (':'))

z = 0

while x > 0: print (z) print () x = x - 1 z = y + z time.sleep (.2)

print (z+x)


回答1:


You can repetitively use addition.

def multiply(a,b):
    total = 0
    counter = 0
    while counter < b:
        total += a
        counter += 1
    return total

>>> multiply(5,3)
15

Think about it, to multiply two integers, you just add one integer that many times. For example:

5 x 3 = 5 + 5 + 5 = 15



回答2:


I'm uncertain if this is a correct answer, because it contains the dreaded *. On the other hand, it's not an arithmetic multiplication... Edit made a mess with the logic, now it's OK

def prod(a,b):
    if a<0 and b<0:
         a, b = -a, -b
    elif b<0:
         b, a = a, b
    return sum([a]*b)



回答3:


I guess if I had to use while and not any multiplication, it'd be with a list? :/

def weird_times(x, y):
    my_factors = [x for _ in range(y)]
    answer = 0
    while my_factors:
        answer += my_factors.pop()
    return answer

>>> weird_times(5, 0)
0
>>> weird_times(5, 1)
5
>>> weird_times(5, 3)
15
>>> 


来源:https://stackoverflow.com/questions/26788813/how-do-you-multiply-using-while-without-using-multiplication

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!