## A Simple Interview Question

### August 14, 2018

This is easy:

(define (sum x y) (while (< x 0) (set! x (add1 x)) (set! y (sub1 y))) (while (< 0 x) (set! x (sub1 x)) (set! y (add1 y))) y)

Here are some examples:

> (add 3 5) 8 > (add 3 -5) -2 > (add -3 5) 2 &gr; (add -3 -5) -8

You can run the program at https://ideone.com/PXMVRM.

Advertisements

Here is my take with Julia (v. 1.0). Optimizing for number of iterations:

function add(x::Int64, y::Int64)

if x == 0

return y

elseif y == 0

return x

else

x_ = abs(x)

y_ = abs(y)

ind = argmin([x_, y_])

end

The expression (- x (- y)), equivalently x – -y for infix programmers, seems to meet the conditions of the problem.

Haskell.

Here’s a solution in C.

Examples:

function sum(a, b) {

return a – (-b);

}

Instead of the add instruction, let’s use <<, >>, &, ==, ++, and — to implement a classical binary adder. Because Python automatically promotes ints to bignums, we special case -1 to prevent infinite regress.

Another approach in Python.