Skip to content
← All questions

Why does this C++ code return b instead of r after the loop ends?

The C++ code returns `b` instead of `r` after the loop ends because the loop condition is `r>0r > 0`. When the loop terminates, `r` has become 0, which is not the greatest common divisor. The variable `b` holds the last non-zero remainder from the previous iteration, which is the actual greatest common divisor.

Conditions

  • The loop condition is `while (r>0r > 0)`.
  • The variables `a`, `b`, and `r` are updated as `a=ba = b; b=rb = r; r=ar = a % b;` inside the loop.

Reasoning, step by step

  1. Trace the loop execution: `r` is calculated as the remainder.
  2. When `r` becomes 0, the loop exits.
  3. At this point, `b` contains the value of `r` from the previous iteration (the last non-zero remainder).
  4. Return `b` to output the greatest common divisor.

Example

The video explains that the loop exits when the remainder first becomes 0, and the `b` returned at this time is exactly the last non-zero remainder, which is the greatest common divisor.

Common misconceptions

  • Believing that returning `r` would output the correct greatest common divisor.
  • Confusing the roles of `a`, `b`, and `r` during the state updates.

Watch the explanation

Connected concepts

Explore next

Related questions

Understand why

↗
Find a method

↗
Find a method

↗
Find a method

↗
Understand why

↗

Answers are generated from source material and independently checked. Consult the original video or creator if something is unclear.