Monday, June 11, 2012

How to Multiply two numbers without using +,- or * Operator



Multiplication is nothing but repeated addition, so as long as you could figure out a way to add two numbers, then repeating them will also provide you product of two numbers.

Since, Python is the best language, I am giving the solution in Python only.

import sys
def recurse(a,b):
  x = a^b
  y = a&b
  if y:
     return recurse(x,y<<1)
  else:
     return x

if __name__ == '__main__':
   a = int(raw_input("Enter value of 'a' --> "))
   b = int(raw_input("Enter value of 'b' --> "))

   product=0
   for i in range(0,b):
       product=recurse(product,a)
   print repr(a) + " x " + repr(b) + " = " + repr(product)

Internally this uses bitwise operations.

----
For more info please contact me at rakeshkumar.techie@gmail.com



Happy Programming -- Happy Hacking

No comments:

Post a Comment