COME ON CODE ON

A blog about programming and more programming.

Multiply two Numbers Without Using * Operator

with 3 comments

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 :

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


NJOY!
-fR0DDY

Written by fR0DDY

April 8, 2010 at 10:05 AM

Posted in Beautiful Codes

Tagged with , ,

3 Responses

Subscribe to comments with RSS.

  1. nice logic :) .I hope that u will come up with some new posts too.

    speed

    April 8, 2010 at 12:53 PM

  2. 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…?

    main()
    {
        int a,b;
        int m=0;
        while (~scanf("%d%d",&a,&b))
        {
         m=0;
          while (a)
          {
            if (a&2)
            {
              if (a&1) m+=b+b+b;//remain 3
              else m+=b+b;//remain 2
            }
            else if(a&1)//remain 1
             m+=b;
            a>>=2;
            b<<=2;
            //printf("%d,%d,%d\n",a,b,m); //to see intermediate values               
          }
            printf("(%d)\n",m);                
        }
    }
    

    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??

    Ritesh

    September 27, 2010 at 12:33 AM

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


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 99 other followers