1

This program is supposed to compute the smallest common multiple. It does not present divisions by zero, nor weird operations (as far as I know), yet it breaks at some point. The program seems to return "Floating point exception (core dumped)" for any pair of values. *Precondition: a >= 1 and b >= 1. The code:

int mcd(int x, int y) { //computes greatest common divisor
    if (x == 0) return y;
    return mcd(y, x % y);
}

int mcm(int x, int y) { //computes smallest common multiple
    return x * y / mcd(x, y);
}

int main() {
    int a, b;
    int counter = 0;
    while (cin >> a >> b) {
        ++counter;
        cout << "#" << counter
        << " : " << mcm(a, b) << endl;
    }
}

What is causing this behaviour?

Álvaro
  • 141
  • 2
  • 14
  • 3
    *It does not present divisions by zero* -- `x % y` -- What happens if `y == 0`? Also, use a debugger and see what is happening step-by-step instead of assuming what is happening. – PaulMcKenzie Oct 14 '18 at 13:28
  • Excuse me, a precondition for the exercise states that y >= 1. – Álvaro Oct 14 '18 at 13:30
  • 2
    @Álvaro -- *Excuse me, a precondition for the exercise states that y >= 1* -- One of the things you will realize is that words can lie. The only thing that tells the truth is the program and what you see when you debug. If we wrote programs and assume things work based on our words (or comments in code), there would be no bugs. – PaulMcKenzie Oct 14 '18 at 13:32
  • It likely doesn't help that you are swapping x and y in `mcd()` between calls – David Hoelzer Oct 14 '18 at 13:43
  • It has to be `if (y==0) return x;` – Rabbid76 Oct 14 '18 at 13:47
  • 1
    @Álvaro [See this](https://www.ideone.com/WjlFIb). You are dividing by 0. One of the preconditions in dividing is that the denominator is not 0. That is only words -- you need to write the code to ensure this. – PaulMcKenzie Oct 14 '18 at 13:47
  • 2
    "On two occasions I have been asked, 'Pray, Mr. Babbage, if you put into the machine wrong figures, will the right answers come out?' I am not able rightly to apprehend the kind of confusion of ideas that could provoke such a question." ~ Charles Babbage – Eljay Oct 14 '18 at 13:58

1 Answers1

3

You are dividing by zero because your stop condition in line 2 is wrong. The right one is:

if (y == 0) return x;

Source: Euclidean Algorithm