#include // This program queries the user for two integers 'm' // and 'n' and calculates their greatest common divisor // using the Euclidean algorithm. // // By convention, the greatest common divisor is // non-negative. In particular, // // gcd(m, 0) = |m|, // gcd(0, n) = |n|, // // and we will define // // gcd(0, 0) = 0. // // Exercises: // // 1. This code does not work if at least one of the // arguments is 0. In particular, it may attempt // to calculate a remainder after division by 0. // // Modify the code so that it correctly handles // cases where either or both arguments are 0. // // 2. If the program crashes with the message // // Floating point exception (core dumped) // // what exact operation in this program causes the // error? // // Is the program actually performing any // floating-point arithmetic? // // 3. Trace the Euclidean algorithm by hand for // // m = 112 // n = 42. // // What are the successive values of 'm', 'n', // and 'rem'? // Function declarations int main(); // Function definitions int main() { int m{}; int n{}; std::cout << "Enter the first integer: "; std::cin >> m; if ( m < 0 ) { m = -m; } std::cout << "Enter the second integer: "; std::cin >> n; if ( n < 0 ) { n = -n; } // Make sure m >= n. if ( m < n ) { int tmp{ m }; m = n; n = tmp; } // Perform the Euclidean algorithm. while ( m%n != 0 ) { int rem{ m%n }; m = n; n = rem; } std::cout << "The gcd is " << n << "." << std::endl; return 0; } // Hint for Exercise 1: // // After making both integers non-negative and // ensuring that m >= n, what can you immediately // conclude if // // n == 0? // // In that case, should the Euclidean algorithm // even be executed? // Hint for Exercise 2: // // Consider the condition of the while loop: // // m%n != 0 // // What operation is performed before the result // can be compared with 0? // // What happens if n == 0? // Here is one solution: /* int main() { int m{}; int n{}; std::cout << "Enter the first integer: "; std::cin >> m; if ( m < 0 ) { m = -m; } std::cout << "Enter the second integer: "; std::cin >> n; if ( n < 0 ) { n = -n; } // Make sure m >= n. if ( m < n ) { int tmp{ m }; m = n; n = tmp; } // If n == 0, then gcd(m, 0) == m. Otherwise, // perform the Euclidean algorithm. if ( n != 0 ) { while ( m%n != 0 ) { int rem{ m%n }; m = n; n = rem; } } else { n = m; } std::cout << "The gcd is " << n << "." << std::endl; return 0; } */ // Explanation of Exercise 2: // // The operation that causes the error is // // m%n // // when // // n == 0. // // The '%' operator calculates the remainder after // integer division. There is no remainder after // division by zero because integer division by zero // is undefined. // // Despite the message // // Floating point exception (core dumped) // // no floating-point calculation occurs in this // program. On some systems, integer division or // remainder by zero generates the same kind of // processor signal that is reported using this // historical message.