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.
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.
decr :: Integral a => a -> a decr = subtract 1 incr :: Integral a => a -> a incr = (+1) add :: Integral a => a -> a -> a add x y | y < 0 = add (decr x) (incr y) | y == 0 = x | y > 0 = add (incr x) (decr y) main = do print $ add (-4) (-5) print $ add (-4) 5 print $ add 4 (-5) print $ add 4 5Here’s a solution in C.
#include <stdio.h> #include <stdlib.h> int add(int a, int b) { while (a > 0) { --a; ++b; } while (a < 0) { ++a; --b; } return b; } int main(int argc, char* argv[]) { if (argc != 3) { fprintf(stderr, "Usage: %s INT INT\n", argv[0]); return EXIT_FAILURE; } int a = atoi(argv[1]); int b = atoi(argv[2]); int result = add(a, b); printf("%d\n", result); return EXIT_SUCCESS; }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.
def add(a, b, carry=0): if a == -1: carry -= 1 a = 0 if b == -1: carry -= 1 b = 0 if a == b == 0: return carry if a & 1: carry += 1 if b & 1: carry += 1 r = add(a >> 1, b >> 1, carry >> 1) << 1 if carry & 1: r += 1 return rAnother approach in Python.
def add(a, b): return 2*a if a == b else (a*a - b*b) // (a - b)