Implementing "Russian peasant multiplication using java

nafhgood :

Here is the code I have written: I'm a beginner programmer and I'm not very efficient with code. Can anyone check if I can improve it?

Here is the link to the method: https://en.wikipedia.org/wiki/Ancient_Egyptian_multiplication#Russian_peasant_multiplication

public static long RussianPeasantMult(long a, long b)
    {   
        int arraylen=1000;
        long[][] results= new long[2][arraylen];
         results[0][0]=a;
         results[1][0]=b;
         int index=1;

         while(results[0][index-1]!=1)
         {
             results[0][index]=results[0][index-1]/2;
             results[1][index]=results[1][index-1]*2;
             index++;
         }
         long sum=0;
         for (int i=0;i<arraylen;i++)
         {
             if(results[0][i]%2==1)
                 sum=sum+results[1][i];
         }
         return sum;
    }
Willem Van Onsem :

You do not need to put elements in arrays, etc. You can use bitwise operations, and update accumulators, like:

public static long RussianPeasantMult(long a, long b) {
    long sum = 0;
    while(a != 0) {
        if((a & 1) == 1) {
            sum += b;
        }
        a >>>= 1;
        b <<= 1;
    }
    return sum;
}

We thus in each iteration we check if the last bit is set or not. In case it is set, we add b to the sum. Regardless of the last bit, we shift a one position to the right, and b one position to the left. We can stop from the moment a is zero (and thus all bits that are set are "shifted out").

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=107130&siteId=1