C++ Program to Implement Russian Peasant Multiplication

C++Server Side ProgrammingProgramming

Russian Peasant algorithm to multiply two numbers. It is a quick algorithm to calculate multiplication of two long numbers.

Algorithm

Begin
   Russianpeasant(num1, num2)
   Int result=0
   while (num2 > 0)
      if (num2 and 1)
         result = result + n;
         num1= num1 left shift 1;
         num2= num2left shift 1;
   return result
End

Example Code

#include <iostream>
using namespace std;
unsigned int russianPeasant(unsigned int n, unsigned int m) {
   int result = 0;
   while (m > 0) {
      if (m & 1)
         result = result + n;
         n = n << 1;
         m = m >> 1;
   }
   return result;
}
int main() {
   cout << russianPeasant(10, 20) << endl;
   cout << russianPeasant(7, 6) << endl;
   return 0;
}

Output

200
42
raja
Published on 15-Mar-2019 11:12:02
Advertisements