Блог пользователя omtheprogrammer1

Автор omtheprogrammer1, история, 2 часа назад, По-английски

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.

  • Проголосовать: нравится
  • +4
  • Проголосовать: не нравится

»
2 часа назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

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

»
2 часа назад, скрыть # |
← Rev. 4  
Проголосовать: нравится 0 Проголосовать: не нравится

oh a nice question,Sure is hard

»
81 минуту назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

Replace the int mid = (l+r)/2 by int mid = l+(r-l)/2 since $$$r-l\ge 0$$$