Reputation: 3179
This is an interview question. We have only two constructs
loop(a)
means loop for a times.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
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
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
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
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