Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement subtraction using only loop and increment

This is an interview question. We have only two constructs

  1. loop(a) means loop for a times.
  2. increment(a) increments a.

Thus to implement a+b one could write

loop(a) {inc(b)} 
return b;

The question is how to implement a-b.

like image 311
Neal Avatar asked Mar 14 '12 11:03

Neal


1 Answers

How about;

a = 10
b = 8
result = 0

loop(b) {
   last = 0
   times = 0;
   loop(a) {
      last = times
      times = inc(times)
   }
   result = a = last
}

result is 2

Js eg;

var a = 10;
var b = 8;
var result;

for (var _b = 0; _b < b; _b++) {
    var last = 0, times = 0, loopa = 0;
    for (var _a = 0; _a < a; _a++) {
        last = times;
        times = inc(times);
    }
    result = a = last;
}

function inc(i) {
    return i + 1;
}

print(result) // 2
like image 82
Alex K. Avatar answered Sep 20 '22 23:09

Alex K.