Saturday, May 12, 2012

Multiply two numbers without using operators

Write a program to multiply two numbers without using + , - or * operators ?



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)

PS: Python rocks!!! and this is the way, it is done internally, that is by using bitwise operations.
----

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



Happy Programming -- Happy Hacking

2 comments:

  1. Can we use logical AND or OR operations ??

    ReplyDelete
  2. Please mail me the solution at buntynineforu@yahoo.com - Thanks

    ReplyDelete