Friday, October 15, 2010


Came along an interesting puzzle so wanted to share.

Write a function that adds two numbers.  You should not use + or any arithmetic operators.

Lets have two number which are fairly large and try to add those two numbers but try a different approach.

987+789 = 1776

Lets just think backwards

+ 789

Carry : 1110.  This is calculated when the first carry is the first digit and the last carry is the last.

Add 1110 and 666 which gives you the ultimate result.

Now lets implement it in source (I am using python)

>>> def sum_without_arithmetic(a,b):
...     if b==0: 
...         return a
...     sum = a^b
...     carry = (a&b)<<1
...     return sum_without_arithmetic(sum, carry)
>>> sum_without_arithmetic(987,789)

No comments: