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

前端 未结 30 1492
别跟我提以往
别跟我提以往 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条回答
  • 2020-12-01 02:27

    If you can use the log function:

    public static final long multiplyUsingShift(int a, int b) {
        int absA = Math.abs(a);
        int absB = Math.abs(b);
    
        //Find the 2^b which is larger than "a" which turns out to be the 
        //ceiling of (Log base 2 of b) == numbers of digits to shift
        double logBase2 = Math.log(absB) / Math.log(2);
        long bits = (long)Math.ceil(logBase2);
    
        //Get the value of 2^bits
        long biggerInteger = (int)Math.pow(2, bits);
    
        //Find the difference of the bigger integer and "b"
        long difference = biggerInteger - absB;
    
        //Shift "bits" places to the left
        long result = absA<<bits;
    
        //Subtract the "difference" "a" times
        int diffLoop = Math.abs(a);
        while (diffLoop>0) {
            result -= difference;
            diffLoop--;
        }
    
        return (a>0&&b>0 || a<0&&b<0)?result:-result;
    }
    

    If you cannot use the log function:

    public static final long multiplyUsingShift(int a, int b) {
        int absA = Math.abs(a);
        int absB = Math.abs(b);
    
        //Get the number of bits for a 2^(b+1) larger number
        int bits = 0;
        int bitInteger = absB;
        while (bitInteger>0) {
            bitInteger /= 2;
            bits++;
        }
    
        //Get the value of 2^bit
        long biggerInteger = (int)Math.pow(2, bits);
    
        //Find the difference of the bigger integer and "b"
        long difference = biggerInteger - absB;
    
        //Shift "bits" places to the left
        long result = absA<<bits;
    
        //Subtract the "difference" "a" times
        int diffLoop = absA;
        while (diffLoop>0) {
            result -= difference;
            diffLoop--;
        }
    
        return (a>0&&b>0 || a<0&&b<0)?result:-result;
    }
    

    I found this to be more efficient:

    public static final long multiplyUsingShift(int a, int b) {
        int absA = Math.abs(a);
        int absB = Math.abs(b);
    
        long result = 0L;
        while (absA>0) {
            if ((absA&1)>0) result += absB; //Is odd
            absA >>= 1;
            absB <<= 1;
        }
    
        return (a>0&&b>0 || a<0&&b<0)?result:-result;
    }
    

    and yet another way.

    public static final long multiplyUsingLogs(int a, int b) {
        int absA = Math.abs(a);
        int absB = Math.abs(b);
        long result = Math.round(Math.pow(10, (Math.log10(absA)+Math.log10(absB))));
        return (a>0&&b>0 || a<0&&b<0)?result:-result;
    }
    
    0 讨论(0)
  • 2020-12-01 02:30

    Let N be the number that we want to multiply with 7.

    N x 7 = N + N + N + N + N + N + N
    N x 7 = N + N + N + N + N + N + N + (N - N)
    N x 7 = (N + N + N + N + N + N + N + N) - N
    N x 7 = 8xN - N
    

    As we know that, left shifting any number by one bit multiply it by 2. Hence, multiplying any number with 8 is equivalent to right shifting it by 3 bits

    N x 7 = (N << 3) - N 
    

    I found this description here http://www.techcrashcourse.com/2016/02/c-program-to-multiply-number-by-7-bitwise-operator.html

    Hope it helps.

    0 讨论(0)
  • 2020-12-01 02:30

    By making use of recursion, we can multiply two integers with the given constraints.

    To multiply x and y, recursively add x y times.

         #include<stdio.h>
         /* function to multiply two numbers x and y*/
         int multiply(int x, int y)
         {
            /* multiplied with anything gives */
            if(y == 0)
            return 0;
    
            /* Add x one by one */
            if(y > 0 )
            return (x + multiply(x, y-1));
    
            /* the case where y is negative */
            if(y < 0 )
            return -multiply(x, -y);
         }
    
         int main()
         {
           printf("\n %d", multiply(5, -11));
           getchar();
           return 0;
         }
    
    0 讨论(0)
  • 2020-12-01 02:31

    Think about the normal multiplication method we use

             1101 x        =>13
             0101          =>5
    ---------------------
             1101
            0000
           1101
          0000
    ===================        
          1000001 .        => 65
    

    Writing the same above in the code

    #include<stdio.h>
    
    int multiply(int a, int b){
        int res = 0,count =0;
        while(b>0) {
            if(b & 0x1)
                res = res + (a << count);
            b = b>>1;
            count++;
        }
        return res;
    }
    int main() {
        printf("Sum of x+y = %d", multiply(5,10));
        return 0;
    }
    
    0 讨论(0)
  • 2020-12-01 02:32

    Think about how you multiply in decimal using pencil and paper:

      12
    x 26
    ----
      72
     24
    ----
     312
    

    What does multiplication look like in binary?

       0111
    x  0101
    -------
       0111
      0000
     0111
    -------
     100011
    

    Notice anything? Unlike multiplication in decimal, where you need to memorize the "times table," when multiplying in binary, you are always multiplying one of the terms by either 0 or 1 before writing it down in the list addends. There's no times table needed. If the digit of the second term is 1, you add in the first term. If it's 0, you don't. Also note how the addends are progressively shifted over to the left.

    If you're unsure of this, do a few binary multiplications on paper. When you're done, convert the result back to decimal and see if it's correct. After you've done a few, I think you'll get the idea how binary multiplication can be implemented using shifts and adds.

    0 讨论(0)
  • 2020-12-01 02:32

    JAVA:
    Considering the fact, that every number can be splitted into powers of two:

    1 = 2 ^ 0
    2 = 2 ^ 1
    3 = 2 ^ 1 + 2 ^ 0
    ...
    

    We want to get x where:
    x = n * m

    So we can achieve that by doing following steps:

    1.   while m is greater or equal to 2^pow:
         1.1  get the biggest number pow, such as 2^pow is lower or equal to m
         1.2  multiply n*2^pow and decrease m to m-2^pow
    2.   sum the results
    

    Sample implementation using recursion:

    long multiply(int n, int m) {
        int pow = 0;
        while (m >= (1 << ++pow)) ;
        pow--;
        if (m == 1 << pow) return (n << pow);
        return (n << pow) + multiply(n, m - (1 << pow));
    }
    

    I got this question in last job interview and this answer was accepted.

    EDIT: solution for positive numbers

    0 讨论(0)
提交回复
热议问题