# 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

Similar to aws's answer, but I found easier to reason about:

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.

-
{"found_math": true, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 0, "mathjax_display_tex": 0, "mathjax_asciimath": 1, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 0, "wp-katex-eq": 0, "align": 0, "equation": 0, "x-ck12": 0, "texerror": 0, "url": "http://math.stackexchange.com/questions/331706/programming-brain-teaser", "fetch_time": 1466987315000000000, "content_mime_type": "text/html", "warc_filename": "crawl-data/CC-MAIN-2016-26/segments/1466783395613.65/warc/CC-MAIN-20160624154955-00178-ip-10-164-35-72.ec2.internal.warc.gz", "warc_record_offset": 194910976, "warc_record_length": 18429, "token_count": 557, "char_count": 1784, "score": 3.5625, "int_score": 4, "crawl": "CC-MAIN-2016-26", "snapshot_type": "latest", "language": "en", "language_score": 0.8814327716827393, "file_path": "/sailhome/yjruan/project/latent-lm/data/processed/finemath-4plus/finemath-4plus/train-00008-of-00064.parquet"}