VOOZH about

URL: https://www.geeksforgeeks.org/dsa/russian-peasant-multiply-two-numbers-using-bitwise-operators/

⇱ Russian Peasant (Multiply two numbers using bitwise operators) - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Russian Peasant (Multiply two numbers using bitwise operators)

Last Updated : 24 Mar, 2025

Given two integers a and b, the task is to multiply them without using the multiplication operator. Instead of that, use the Russian Peasant Algorithm.

Examples:

Input: a = 2, b = 5
Output: 10
Explanation: Product of 2 and 5 is 10.

Input: a = 6, b = 9
Output: 54
Explanation: Product of 6 and 9 is 54.

Input: a = 8, b = 8
Output: 64
Explanation: Product of 8 and 8 is 64.

The idea is to break multiplication into a series of additions using the Russian Peasant Algorithm. Instead of directly multiplying a and b, we repeatedly halve b and double a, leveraging the fact that multiplication can be rewritten as repeated addition. If b is odd at any step, we add a to the result since that part of the multiplication cannot be handled by doubling alone. This process continues until b becomes zero.

Steps to implement the above idea:

  • Initializeresult to 0.
  • Loop whileb > 0.
  • Ifb is odd, adda to result.
  • Doublea and halveb.
  • Repeat until b becomes 0.
  • Return result

How does this work?  The value of a*b is same as (a*2)*(b/2) if b is even, otherwise the value is same as ((a*2)*(b/2) + a). In the while loop, we keep multiplying β€˜a’ with 2 and keep dividing β€˜b’ by 2. If β€˜b’ becomes odd in loop, we add β€˜a’ to β€˜res’. When value of β€˜b’ becomes 1, the value of β€˜res’ + β€˜a’, gives us the result. 


Output
10

Time Complexity: O(log b), each iteration halves b, leading to logarithmic iterations.
Space Complexity: O(1), only a few integer variables are used, requiring constant space.

Comment
Article Tags: