omtheprogrammer1's blog

By omtheprogrammer1, history, 52 minutes ago, In English

Okay, here's a challenge.

The code below is supposed to find the smallest integer x for which check(x) returns false, assuming check(x) is true for all smaller values and false for all larger values.

It compiles, and the logic looks pretty normal.

int l = -10, r = 10;

while (l < r) {
    int mid = (l + r) / 2;

    if (check(mid)) {
        l = mid + 1;
    }
    else {
        r = mid;
    }
}

Here, check(x) returns: - true if x is smaller than the target. - false if x is greater than or equal to the target.

Find a valid target for which this code gets stuck or fails.

Rules: - Give the smallest counterexample you can find. - Explain why the code fails. - Bonus: Fix it without changing the overall approach.

Try to find the bug before opening the comments.

Let's see who catches it first.

  • Vote: I like it
  • +2
  • Vote: I do not like it

»
52 minutes ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by omtheprogrammer1 (previous revision, new revision, compare).

»
44 minutes ago, hide # |
← Rev. 4  
Vote: I like it 0 Vote: I do not like it

oh a nice question,Sure is hard