#include // Write a program to find the greatest common // divisor of two non-negative integers with the // following requirements: // // gcd( 0, 0 ) = 0 // gcd( 0, n ) = n // gcd( m, 0 ) = m // // Otherwise, the gcd is the largest positive // integer that divides both integers. // // If either integer is negative, return 0. // // Note that the only tool you have right now is // a for loop, so this is not the most efficient // way to solve this problem. Later, we will see // a much more efficient algorithm. // Function declarations int main(); // Function definitions int main() { return 0; } // Hint: An integer 'k' divides an integer 'm' // if m%k == 0. // // If both integers are positive, how large // could their greatest common divisor possibly // be? // Here is one solution, but scroll down for // a better solution. /* int main() { int m{}; std::cout << "Enter a non-negative integer: "; std::cin >> m; int n{}; std::cout << "Enter another non-negative integer: "; std::cin >> n; if ( (m < 0) || (n < 0) ) { return 0; } if ( m == 0 ) { std::cout << "gcd(" << m << ", " << n << ") = " << n << std::endl; return 0; } if ( n == 0 ) { std::cout << "gcd(" << m << ", " << n << ") = " << m << std::endl; return 0; } int smaller{ m }; if ( n < smaller ) { smaller = n; } int gcd{ 1 }; for ( int k{ 2 }; k <= smaller; ++k ) { if ( (m%k == 0) && (n%k == 0) ) { gcd = k; } } std::cout << "gcd(" << m << ", " << n << ") = " << gcd << std::endl; return 0; } */ // Here is a better solution. Why is it better? /* int main() { int m{}; std::cout << "Enter a non-negative integer: "; std::cin >> m; int n{}; std::cout << "Enter another non-negative integer: "; std::cin >> n; if ( (m < 0) || (n < 0) ) { return 0; } if ( m == 0 ) { std::cout << "gcd(" << m << ", " << n << ") = " << n << std::endl; return 0; } if ( n == 0 ) { std::cout << "gcd(" << m << ", " << n << ") = " << m << std::endl; return 0; } int smaller{ m }; if ( n < smaller ) { smaller = n; } for ( int k{ smaller }; k >= 1; --k ) { if ( (m%k == 0) && (n%k == 0) ) { std::cout << "gcd(" << m << ", " << n << ") = " << k << std::endl; // We started with the largest possible // divisor and worked downward, so the // first common divisor must be the gcd. return 0; } } // We should never reach this statement because // 1 divides every positive integer. std::cout << "We should never get here..." << std::endl; return 0; } */