How can I perform multiplication without the '*' operator?

前端 未结 30 1584
别跟我提以往
别跟我提以往 2020-12-01 01:47

I was just going through some basic stuff as I am learning C. I came upon a question to multiply a number by 7 without using the * operator. Basically it\'s like this

<
30条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-01 02:37

    O(log(b)) method

    public int multiply_optimal(int a, int b) {
    
        if (a == 0 || b == 0)
            return 0;
        if (b == 1)
            return a;
        if ((b & 1) == 0)
            return multiply_optimal(a + a, b >> 1);
        else
            return a + multiply_optimal(a + a, b >> 1);
    
    }
    

    The resursive code works as follows:
    Base case:
    if either of the number is 0 ,product is 0.
    if b=1, product =a.

    If b is even:
    ab can be written as 2a(b/2)
    2a(b/2)=(a+a)(b/2)=(a+a)(b>>1) where'>>' arithematic right shift operator in java.

    If b is odd:
    ab can be written as a+a(b-1)
    a+a(b-1)=a+2a(b-1)/2=a+(a+a)(b-1)/2=a+(a+a)((b-1)>>1)
    Since b is odd (b-1)/2=b/2=b>>1
    So ab=a+(2a*(b>>1))
    NOTE:each recursive call b is halved => O(log(b))

提交回复
热议问题