Reputation: 141
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?
Upvotes: 1
Views: 84
Reputation: 51
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
Upvotes: 3