Home » C++ programs

C++ program to multiply two numbers without using multiplication operator

Here, we are going to learn how to multiply two numbers without using multiplication operator using Russian peasant algorithm?
Submitted by Vivek Kothari, on November 17, 2018

The problem is we have two integer numbers and find the multiplication of them without using the multiplication operator. This problem can be solved using the Russian peasant algorithm. Assume the two given numbers are m and n. Initialize mul with 0 and repeat following steps while n is greater than zero :

  1. Add m to mul, if n is odd
  2. Double the value of m and half the value of n.

Here we use properties of << (left shift) and >> (right shift) operators for doubling the value of m and for dividing the value of ‘n by 2.

Reference: Russian peasant multiplication

C++ program to implement Russian peasant algorithm

#include <iostream> 
using namespace std; 

int Multiply(int m, int n) 
{
	int mul=0; 

	while (n > 0) 
	{
		// if n is odd
		if (n & 1) mul = mul + m; 

		// Double 'm' and halve 'n' 
		m = m << 1; 
		n = n >> 1; 
	} 

	return mul;
} 

int main() {
	int ans;

	ans=Multiply(2,3);
	cout<<"Multiplication of 2 and 3 = "<<ans<<endl;

	ans=Multiply(10,10);
	cout<<"Multiplication of 10 and 10 = "<<ans<<endl;

	return 0; 
} 

Output

Multiplication of 2 and 3 = 6
Multiplication of 10 and 10 = 100




Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.