## Multiply two Numbers Without Using * Operator

Lets have a fun question. **Multiply two numbers without using the * operator.**

Here’s the code in C/C++:

main(a,b,m) { while (~scanf("%d%d",&a,&b)) { m=0; while (a) { if (a&1) m+=b; a>>=1; b<<=1; } printf("%d\n",m); } }

The above code is a implementation of an algorithm better known as the Ethiopian Multiplication or the Russian Peasant Multiplication.

Here’s the algorithm :

```
```
- Let the two numbers to be multiplied be a and b.
- If a is zero then break and print the result.
- If a is odd then add b to the result.
- Half a, Double b. Goto Step 2.

NJOY!

-fR0DDY

nice logic🙂.I hope that u will come up with some new posts too.

speedApril 8, 2010 at 12:53 PM

dear i guess this wont work if a is -ve no. so condition to check that must be applied before carrying out multiplication

here is same code with some modification

#include

using namespace std;

int main()

{

int a=5,b=7,c=0,ch=5,flag;

while(ch)

{ flag=0;

cout<>a>>b;

c=0;

if(a0)

{

if(a & 1)

c=c+b;

a>>=1;

b<<=1;

cout<<"\n loop executed";

}

if(flag)

{c=-c;}

cout<<"\n *** multi plication of the 2 is : "<>a;

return 0;

}

rahulAugust 22, 2012 at 1:39 PM

2. number multiply by 2 with out using * operator

#include

main()

{

int num = 5;

num = num<<1;

printf("%d",num);

}

Op : 10

Exp : num number left shift by the 1 position we can get.

1st—————0101

2nd————–1010

prawinFebruary 12, 2013 at 1:01 PM

Hi gaurav…

Nice coding🙂 . I enjoyed working around the codes tried an extended version of the code above.. can you suggest me which of the codes will take less resources…?

As you can see that this algorithm can be extented to higher form in (multiple of 8,16,32,64..). which of the algorithm will be best suited for normal calculations??

RiteshSeptember 27, 2010 at 12:33 AM

[…] this I like Categories: Code LikeBe the first to like this post. Comments (0) Trackbacks (0) Leave a […]

multiply two numbers without using * operator « AfroCoder'sJanuary 28, 2011 at 8:14 PM

#include

main()

{

int x=10, y=10, z;

int mult = 0;

for ( z = 1 ; z <= x ; z++)

mult = mult + y;

printf("The multiplication of two numbers: %ld\n",mult);

return 0;

}

usuf16March 8, 2013 at 8:03 PM

thanxx for such a easy way…

nehaOctober 13, 2013 at 12:59 PM