#include // Write a program to find the least common // multiple of two non-negative integers with the // following requirements: // // lcm( 0, 0 ) = 0 // lcm( 0, n ) = 0 // lcm( m, 0 ) = 0 // // Otherwise, the lcm is the smallest positive // integer that is divisible by both 'm' and 'n'. // // 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' is divisible by an // integer 'm' if k%m == 0. // // If both 'm' and 'n' are positive, what is // the smallest possible value of their lcm? // What value is guaranteed to be a common // multiple of both? // 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) || (n == 0) ) { std::cout << "lcm(" << m << ", " << n << ") = 0" << std::endl; return 0; } int larger{ m }; if ( n > larger ) { larger = n; } // The lcm cannot be smaller than the larger // operand, while m*n is guaranteed to be a // common multiple of both operands. for ( int k{ larger }; k <= m*n; ++k ) { if ( (k%m == 0) && (k%n == 0) ) { std::cout << "lcm(" << m << ", " << n << ") = " << k << std::endl; // We searched upward, so the first common // multiple we find must be the lcm. return 0; } } // We should never reach this statement because // m*n is a common multiple of positive m and n. std::cout << "We should never get here..." << std::endl; return 0; } */ // Here is a better solution: // // m*n // lcm( m, n ) = ------------------------- // gcd( m, n ) // // Why is this 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) || (n == 0) ) { std::cout << "lcm(" << m << ", " << n << ") = 0" << 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) ) { // We have found gcd( m, n ), so we can // use it to calculate lcm( m, n ). std::cout << "lcm(" << m << ", " << n << ") = " << (m*n)/k << std::endl; 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; } */