programming brain teaser

2.9k Views Asked by At

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.

2

There are 2 best solutions below

1
On

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.

2
On
a = 0;    
b = 5;   //Random number
c = 0;

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

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