Thursday, July 24, 2008

Question #4 - C - Multiply two numbers without using arithmetic operators

 

Question #4 - C - Multiply two numbers without using arithmetic operators

 

   Note: I don't want any arithmetic operators. It is easier now as we have uncovered addition.

 

There is one more question I want to give, so, hurry-up and send the answers as quickly as possible.

 

 

>>>>

Sri

>>>>>>>>> 

#include <stdio.h>
      int multiply(int x, int y)
      {
    int product=0;
     while (y!=0)
  {
   if(y&01)
    product=product+x;
   x<<=1;
   y>>=1;
  }
  return product;
  printf("The product is: %d",product);
   }

 

      int main()
      {
     int a,b;
  printf("Enter the two numbers: \n");

 

     scanf("%d",&a);
     scanf("%d",&b);
     printf("Product is: %d",multiply(a,b));
      }

>>>>>>>> 

Santosh

>>>>>>> 

#include "stdafx.h"
#include <stdio.h>
#include <conio.h>

 

int add(int c, int d)
{
 if (!c)
  return d;
    else
  return add((c & d) << 1, c ^ d);
}

 

void main()
{
   int a,b,result;
   printf("Enter the numbers to be multiplied :");
   scanf("%d%d",&a,&b);
   result=0;
   while(b != 0)             
   {
      if (b&01)
    result = add(result, a);
      a<<=1;
      b>>=1;
   }
   printf("Result:%d",result);
   getch();

>>>> 

Rajini

>>>> 

int add(int a, int b)
{
    if (!a) return b;
    else
         return add((a & b) << 1, a ^ b);
}

 

int fnMultiply(int a, int b)
{

 int iR = a;

 

 for(int i=1;i<b;i++)
 {
  iR = add(iR,a);
 }

 

 return iR;

 

}

>>> 

Kiran

<<< 

#include<stdio.h>
int add(int,int);

 

void main()

 

{  int a,b,mul=0,i;

 

   printf("enter 2 numbers to be multiplied\n");
   scanf("%d%d",&a,&b);

 

   for(i=0;i<16;i++)

 

   if(b&(1<<i))
      mul= add(a<<i,mul);
     
   printf("%d\n",mul);

 

}


int add(int b, int a)
{
 int c=0,s=0,k,ai,bi,i;

 

 for(i=0;i<16;i++)

 

      {
            ai = ((a>>i)&1);
            bi = ((b>>i)&1);
            k = ((((ai^bi)^c))<<i);
            s = s|k;
          c = (ai&c) | (bi&c) | (ai&bi); 

 

      }
 return(s);
}

 

 

 

 

Question #4 - C - Multiply two numbers without using arithmetic operators

 

   Note: I don't want any arithmetic operators. It is easier now as we have uncovered addition.

 

There is one more question I want to give, so, hurry-up and send the answers as quickly as possible.

 

 

Regards,

Bhimsen Joshi



--
At a certain point there is no difference between Magic and Science.
-Bhimsen Joshi

No comments: