Neal
Neal

Reputation: 3179

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.

Upvotes: 7

Views: 4252

Answers (5)

wynnej1983
wynnej1983

Reputation: 1

RESET B
INC B
LOOP A
{
    INC D
    LOOP B
    {
        RESET D
    }
}

Upvotes: -1

Neal
Neal

Reputation: 3179

I think if break from loop is allowed, a-b can be done in this way:

c=0;
loop(a) {
    if (a==b) break;
    inc(c);
    inc(b);
}
return c;

Ofcourse assuming a>b.

Upvotes: 3

Alex K.
Alex K.

Reputation: 175986

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

Upvotes: 11

Tomer W
Tomer W

Reputation: 3443

depends if this Numeric architecture is known:

you can take advantage of the "Two Compliment" mechanism of the x86/x64 architecture,

for example, if the signed numbering scheme is cyclic like.

f(0 < x < 32768)     = x
f(32769 < x < 65535) = x - 65536

Then you can use:

dec(a)
{
    loop(65535 [= 2^16-1]) { inc(a) }
}

.

solving the riddel as

(a-b)
{
   loop(b) { dec(a) }
}

Depending on the Signed scheme the addition Constant can change, same for short, long, large integer types.

Hope this is good :) Best of luck.

Upvotes: 1

moodywoody
moodywoody

Reputation: 2159

We're a looking for x, so that a-b = x. In other words a = b+x

Pseudocode

int x = 0

WHILE (x <= a) do {

if (b+x == a) BREAK // satisfies a-b = x

x++

}

Upvotes: 0

Related Questions