How to implement subtraction using only loop and increment

This is an interview question. We have only two designs

  • loop(a) means a loop for time.
  • increment(a) increases a.

Thus, to implement a + b, we can write

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

The question is how to implement ab.

+6
source share
5 answers

What 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 
+9
source

I think that if you allow a break from the loop, ab can be done as follows:

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

Suppose a> b.

+3
source

Depends on this numerical architecture:

you can use the "Two compliments" mechanism of x86 / x64 architecture,

for example, if the signed numbering scheme is cyclic.

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

Then you can use:

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

.

riddle decision how

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

Depending on the signed scheme, the add constant may change, the same for short, long, large integer types.

Hope this is good :) Good luck.

+1
source

We are looking for x, so ab = x. In other words, a = b + x

Pseudo code

int x = 0

WHILE (x <= a) do {

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

x ++

}

0
source
 RESET B INC B LOOP A { INC D LOOP B { RESET D } } 
-1
source

Source: https://habr.com/ru/post/910696/


All Articles