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

前端 未结 30 1493
别跟我提以往
别跟我提以往 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:39

    @Wang, that's a good generalization. But here is a slightly faster version. But it assumes no overflow and a is non-negative.

    int mult(int a, int b){
        int p=1;
        int rv=0;
        for(int i=0; a >= p && i < 31; i++){
            if(a & p){
                rv += b;
            }
            p = p << 1;
            b = b << 1;
        }
    
        return rv;
    }
    

    It will loop at most 1+log_2(a) times. Could be faster if you swap a and b when a > b.

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

    It is the same as x*8-x = x*(8-1) = x*7

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

    Everyone is overlooking the obvious. No multiplication is involved:

    10^(log10(A) + log10(B))
    
    0 讨论(0)
  • 2020-12-01 02:42

    Any number, odd or even, can be expressed as a sum of powers of two. For example,

         1   2   4   8
    ------------------
     1 = 1
     2 = 0 + 2
     3 = 1 + 2
     4 = 0 + 0 + 4
     5 = 1 + 0 + 4
     6 = 0 + 2 + 4
     7 = 1 + 2 + 4
     8 = 0 + 0 + 0 + 8
    11 = 1 + 2 + 0 + 8
    

    So, you can multiply x by any number by performing the right set of shifts and adds.

     1x = x
     2x = 0 + x<<1
     3x = x + x<<1
     4x = 0 +  0   + x<<2
     5x = x +  0   + x<<2
    11x = x + x<<1 +   0  + x<<3
    
    0 讨论(0)
  • 2020-12-01 02:42
    import java.math.BigInteger;
    
    public class MultiplyTest {
        public static void main(String[] args) {
            BigInteger bigInt1 = new BigInteger("5");
            BigInteger bigInt2 = new BigInteger("8");
            System.out.println(bigInt1.multiply(bigInt2));
        }
    }
    
    0 讨论(0)
  • 2020-12-01 02:42
    public static void main(String[] args) {
        System.out.print("Enter value of A -> ");
        Scanner s=new Scanner(System.in);
        double j=s.nextInt();
        System.out.print("Enter value of B -> ");
        Scanner p=new Scanner(System.in);
        double k=p.nextInt();
        double m=(1/k);
        double l=(j/m);
        System.out.print("Multiplication of A & B=> "+l);
    }
    
    0 讨论(0)
提交回复
热议问题