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.

/* function to multiply two numbers x and y*/
int multiply(int x, int y)
   /* 0  multiplied with anything gives 0 */
   if(y == 0)
     return 0;

   /* Add x one by one */ 
   if(y > 0 )
     return (x + multiply(x, y-1));
  /* the case where y is negative */ 
   if(y < 0 )
     return -multiply(x, -y);

int main()
  printf("\n %d", multiply(5, -11));
  return 0;

Time Complexity: O(y) where y is the second argument to function multiply().

Russian Peasant (Multiply two numbers using bitwise operators)

Please write comments if you find any of the above code/algorithm incorrect, or find better ways to solve the same problem.

GATE CS Corner    Company Wise Coding Practice

Writing code in comment? Please use, generate link and share the link here.