# programming brain teaser

Given a programming language where you could make as many variables up as possible and you could only perform these three operators find b-1.

a=0;
b++;
loop(c){  // This loop will loop exactly c times

}


an example to find the number 2.

a = 0;
a ++;
a ++; // 2


How would you find b-1, where b is any positive integer? There are no signed numbers in this language.

-
Initialize a to 0 and then {increment and test for equality with b-1} in the loop? –  alancalvitti Mar 16 '13 at 1:35
@alancalvitti: There's no test for equality. –  joriki Mar 16 '13 at 1:35
Please don't vandalize questions. –  robjohn Mar 16 '13 at 3:47

It seems that the trick to this question is that for c = 0, loop(c){} loops zero times, ie does nothing. Therefore the following program will work:

a=0;
c=0;
loop(b){
loop(c){
a++;
}
c=0;
c++;
}


We end up with b-1 in a.

-
Very nice solution. –  joriki Mar 16 '13 at 1:40
a = 0;
b = 5;   //Random number
c = 0;

loop(b){
a = c;
c ++;
}

//c holds value 5
//a holds value 4

-
You can't use b = 5, a = c, only setting to zero is allowed. –  Thomas Mar 16 '13 at 7:28
@Thomas The statement b=5 is irrelevant, but the statement a=c can easily be replaced by a=0; loop(c) {a++;}, making this similar to the other answer but IMO a bit more standard to programmers (it's the same logic used to crawl to the end of a data structure). –  Erick Wong Mar 16 '13 at 7:53

c=0;
loop(b){
a=0;
// at the beginning of the loop, c lags the counter by 1
loop(c){
a++;
}
// at the end of the loop, c == counter
// in the last loop, c is set to b but 'a' still lags by 1
c++;
}


This answer is obviously less efficient, looping something like (b-2) + (b-3) + ... + (b-b) more times.

-