The Wayback Machine - https://web.archive.org/web/20240611094750/https://www.geeksforgeeks.org/russian-peasant-multiply-two-numbers-using-bitwise-operators/
Open In App

Russian Peasant (Multiply two numbers using bitwise operators)

Last Updated : 28 Oct, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Given two integers, write a function to multiply them without using multiplication operator.
There are many other ways to multiply two numbers (For example, see this). One interesting method is the Russian peasant algorithm. The idea is to double the first number and halve the second number repeatedly till the second number doesn’t become 1. In the process, whenever the second number become odd, we add the first number to result (result is initialized as 0) 
The following is simple algorithm. 

Let the two given numbers be 'a' and 'b'
1) Initialize result 'res' as 0.
2) Do following while 'b' is greater than 0
   a) If 'b' is odd, add 'a' to 'res'
   b) Double 'a' and halve 'b'
3) Return 'res'. 

 

C++




#include <iostream>
using namespace std;
 
// A method to multiply two numbers using Russian Peasant method
unsigned int russianPeasant(unsigned int a, unsigned int b)
{
    int res = 0; // initialize result
 
    // While second number doesn't become 1
    while (b > 0)
    {
        // If second number becomes odd, add the first number to result
        if (b & 1)
            res = res + a;
 
        // Double the first number and halve the second number
        a = a << 1;
        b = b >> 1;
    }
    return res;
}
 
// Driver program to test above function
int main()
{
    cout << russianPeasant(18, 1) << endl;
    cout << russianPeasant(20, 12) << endl;
    return 0;
}


Java




// Java program for Russian Peasant Multiplication
import java.io.*;
 
class GFG
{
    // Function to multiply two
    // numbers using Russian Peasant method
    static int russianPeasant(int a, int b)
    {
        // initialize result
        int res = 0; 
  
        // While second number doesn't become 1
        while (b > 0)
        {
             // If second number becomes odd,
             // add the first number to result
             if ((b & 1) != 0)
                 res = res + a;
  
            // Double the first number
            // and halve the second number
            a = a << 1;
            b = b >> 1;
        }
        return res;
    }
     
    // driver program
    public static void main (String[] args)
    {
        System.out.println(russianPeasant(18, 1));
        System.out.println(russianPeasant(20, 12));
    }
}
 
// Contributed by Pramod Kumar


Python 3




# A method to multiply two numbers
# using Russian Peasant method
 
# Function to multiply two numbers
# using Russian Peasant method
def russianPeasant(a, b):
 
    res = 0 # initialize result
 
    # While second number doesn't
    # become 1
    while (b > 0):
     
        # If second number becomes
        # odd, add the first number
        # to result
        if (b & 1):
            res = res + a
 
        # Double the first number
        # and halve the second
        # number
        a = a << 1
        b = b >> 1
     
    return res
 
# Driver program to test
# above function
print(russianPeasant(18, 1))
print(russianPeasant(20, 12))
# This code is contributed by
# Smitha Dinesh Semwal


C#




// C# program for Russian Peasant Multiplication
using System;
 
class GFG {
     
    // Function to multiply two
    // numbers using Russian Peasant method
    static int russianPeasant(int a, int b)
    {
        // initialize result
        int res = 0;
 
        // While second number doesn't become 1
        while (b > 0) {
             
            // If second number becomes odd,
            // add the first number to result
            if ((b & 1) != 0)
                res = res + a;
 
            // Double the first number
            // and halve the second number
            a = a << 1;
            b = b >> 1;
        }
        return res;
    }
 
    // driver program
    public static void Main()
    {
        Console.WriteLine(russianPeasant(18, 1));
        Console.WriteLine(russianPeasant(20, 12));
    }
}
 
// This code is contributed by Sam007.


PHP




<?php
// PHP Code to multiply two numbers
// using Russian Peasant method
 
// function returns the result
function russianPeasant($a, $b)
{
     
    // initialize result
    $res = 0;
 
    // While second number
    // doesn't become 1
    while ($b > 0)
    {
         
        // If second number becomes odd,
        // add the first number to result
        if ($b & 1)
            $res = $res + $a;
 
        // Double the first number and
        // halve the second number
        $a = $a << 1;
        $b = $b >> 1;
    }
    return $res;
}
 
    // Driver Code
    echo russianPeasant(18, 1), "\n";
    echo russianPeasant(20, 12), "\n";
     
// This code is contributed by Ajit
?>


Javascript




<script>
 
// A method to multiply two numbers using Russian Peasant method
function russianPeasant(a, b)
{
    var res = 0; // initialize result
 
    // While second number doesn't become 1
    while (b > 0)
    {
     
        // If second number becomes odd, add the first number to result
        if (b & 1)
            res = res + a;
 
        // Double the first number and halve the second number
        a = a << 1;
        b = b >> 1;
    }
    return res;
}
 
// Driver program to test above function
document.write(russianPeasant(18, 1)+"<br>");
document.write(russianPeasant(20, 12));
     
    // This code is contributed by noob2000.
</script>


Output: 

18
240

Time Complexity: O(log2b)

Auxiliary Space: O(1)

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. 
Note that when ‘b’ is a power of 2, the ‘res’ would remain 0 and ‘a’ would have the multiplication. See the reference for more information.
Reference: 
http://mathforum.org/dr.math/faq/faq.peasant.html
This article is compiled by Shalki Agarwal.
 



Previous Article
Next Article

Similar Reads

Multiply two integers without using multiplication, division and bitwise operators, and no loops
By making use of recursion, we can multiply two integers with the given constraints. To multiply x and y, recursively add x y times. Approach: Since we cannot use any of the given symbols, the only way left is to use recursion, with the fact that x is to be added to x y times. Base case: When the numbers of times x has to be added becomes 0. Recurs
9 min read
Calculate Bitwise OR of two integers from their given Bitwise AND and Bitwise XOR values
Given two integers X and Y, representing Bitwise XOR and Bitwise AND of two positive integers, the task is to calculate the Bitwise OR value of those two positive integers. Examples: Input: X = 5, Y = 2 Output: 7 Explanation: If A and B are two positive integers such that A ^ B = 5, A &amp; B = 2, then the possible value of A and B is 3 and 6 respe
7 min read
Multiply a number by 15 without using * and / operators
Given a integer N, the task is to multiply the number with 15 without using multiplication * and division / operators. Examples: Input: N = 10 Output: 150 Input: N = 7 Output: 105 Method 1: We can multiply integer N by 15 using bitwise operators. First left shift the number by 4 bits which is equal to (16 * N) then subtract the original number N fr
6 min read
Total pairs in an array such that the bitwise AND, bitwise OR and bitwise XOR of LSB is 1
Given an array arr[] of size N. The task is to find the number of pairs (arr[i], arr[j]) as cntAND, cntOR, and cntXOR such that: cntAND: Count of pairs where bitwise AND of least significant bits is 1.cntOR: Count of pairs where bitwise OR of least significant bits is 1.cntXOR: Count of pairs where bitwise XOR of least significant bits is 1. Exampl
7 min read
Maximize count of pairs whose Bitwise AND exceeds Bitwise XOR by replacing such pairs with their Bitwise AND
Given an array arr[] consisting of N positive integers, replace pairs of array elements whose Bitwise AND exceeds Bitwise XOR values by their Bitwise AND value. Finally, count the maximum number of such pairs that can be generated from the array. Examples: Input: arr[] = {12, 9, 15, 7}Output: 2Explanation:Step 1: Select the pair {12, 15} and replac
9 min read
Multiply any Number with 4 using Bitwise Operator
We are a Number n and our task is to multiply the number by 4 using a bit-wise Operator. Examples: Input : 4 Output :16 Input :5 Output :20 Explanation Case 1:- n=4 the binary of 4 is 100 and now shifts two bit right then 10000 now the number is 16 is multiplied 4*4=16 ans. Approach :- (n&lt;&lt;2) shift two bit right C/C++ Code // C++ program to m
3 min read
Compute maximum of two integers in C/C++ using Bitwise Operators
Given two integers A and B, the task is to find the maximum of two numbers using Bitwise Operators. Examples: Input: A = 40, B = 54Output: 54 Input: A = -1, B = -10Output: -1 Approach: The idea is to use the Bitwise Operator as well as the Right Shift Operator to find the greatest number between two distinct numbers without using any conditional st
4 min read
Multiply two numbers represented as linked lists into a third list
Given two numbers represented by linked lists, write a function that returns the head of the new linked list that represents the number that is the product of those numbers. Examples: Input : 9-&gt;4-&gt;6 8-&gt;4 Output : 7-&gt;9-&gt;4-&gt;6-&gt;4 Input : 9-&gt;9-&gt;9-&gt;4-&gt;6-&gt;9 9-&gt;9-&gt;8-&gt;4-&gt;9 Output : 9-&gt;9-&gt;7-&gt;9-&gt;5-
21 min read
C Program to Multiply two Floating Point Numbers
Floating point numbers are a way to represent real numbers with both whole parts and fractional parts. In this article, we will learn how to write a C program to find the product of two floating-point numbers. The below image shows an example of floating point multiplication in C: C Program To Multiply Two Floating-Point Numbers The below C program
1 min read
Multiply two numbers of different base and represent product in another given base
Given two numbers N, M in the bases X, Y and another base P. The task is to find the product of N and M and represent the product in base P. Examples: Input: N = 101, M = 110, X = 2, Y = 2, P = 16Output:1EExplanation: NX * MY = (101)2 * (110)2 = (11110)2(11110)2 = (1E)16 Input: N = 101, M = A, X = 2, Y = 20, P = 16Output: 32Explanation: Nx = (101)2
10 min read
Article Tags :
Practice Tags :