algorithm to simulate multiplication by addition

徘徊边缘 提交于 2019-12-24 09:49:06

问题


How to design an algorithm to simulate multiplication by addition. input two integers. they may be zero, positive or negative..


回答1:


def multiply(a, b):                                                                                                                                                               
    if (a == 1):
        return b
    elif (a == 0):
        return 0
    elif (a < 0):
        return -multiply(-a, b)
    else:
        return b + multiply(a - 1, b)



回答2:


some pseudocode:

function multiply(x, y)
  if abs(x) = x and abs(y) = y or abs(x) <> x and abs(y) <> y then sign = 'plus'
  if abs(x) = x and abs(y) <> y or abs(x) <> x and abs(y) = y then sign = 'minus'

 res = 0
 for i = 0 to abs(y)
  res = res + abs(x)
 end

 if sign = 'plus' return res
    else return -1 * res

end function



回答3:


val:= 0
bothNegative:=false

if(input1 < 0) && if(input2 < 0)
  bothNegative=true
if(bothNegative)
  smaller_number:=absolute_value_of(smaller_number)
for [i:=absolute_value_of(bigger_number);i!=0;i--]
do val+=smaller_number

return val;



回答4:


    mul(a,b)
    {
    sign1=sign2=1;
    if(a==0 || b==0)
return 0;
if(a<0){
    sign1=-1;
    a=-a;
    }
    if(b<0){
    sign2=-1;
    b=-b;
    }
    s=a;
    for(i=1;i<b;i++)
    s+=a;
    if(sign1==sign2)
    return s;
    else
    return -s;
    }



回答5:


How about this for integers:

int multiply(int a, int b)
{
    int product = 0;
    int i;
    if ( b > 0 )
    {
        for(i = 0; i < b ; i++)
        {
            product += a;
        }
    }
    else
    {
        for(i = 0; i > b ; i--)
        {
            product -= a;
        }
    }

    return product;
}


来源:https://stackoverflow.com/questions/6577828/algorithm-to-simulate-multiplication-by-addition

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