[Math] programming brain teaser

algorithmspuzzle

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.

Best Answer

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.

Related Question