08/02/2025
08/02/2025
08/02/2025
#include <iostream>
#include <numeric> // For std::gcd and std::lcm (C++17 and later)
// Function to calculate Greatest Common Divisor (GCD) using Euclidean algorithm
int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
// Function to calculate Least Common Multiple (LCM)
int lcm(int a, int b) {
return (a * b) / gcd(a, b);
}
int main() {
int a, b;
std::cout << "Enter two integers a and b: ";
std::cin >> a >> b;
// Calculate GCD
int greatestCommonDivisor = gcd(a, b);
std::cout << "Greatest Common Divisor (GCD) of " << a << " and " << b << " is: " << greatestCommonDivisor << std::endl;
// Calculate LCM
int leastCommonMultiple = lcm(a, b);
std::cout << "Least Common Multiple (LCM) of " << a << " and " << b << " is: " << leastCommonMultiple << std::endl;
// Alternative using C++17 <numeric> library:
// int greatestCommonDivisorCpp17 = std::gcd(a, b);
// int leastCommonMultipleCpp17 = std::lcm(a, b);
// std::cout << "GCD (C++17): " << greatestCommonDivisorCpp17 << std::endl;
// std::cout << "LCM (C++17): " << leastCommonMultipleCpp17 << std::endl;
return 0;
}
Explanation and Improvements:
Include <iostream>: This is necessary for input and output operations (like std::cout and std::cin).
GCD Function (Euclidean Algorithm): The gcd() function efficiently calculates the Greatest Common Divisor using the Euclidean algorithm. This is the standard and most efficient way to find the GCD.
LCM Function: The lcm() function calculates the Least Common Multiple using the relationship: LCM(a, b) = (a * b) / GCD(a, b).
Input: The program prompts the user to enter two integers a and b.
Output: The program then prints the calculated GCD and LCM of the two numbers.
C++17 <numeric> Library (Optional): If you are using C++17 or a later standard, you can use the <numeric> library's std::gcd and std::lcm functions directly. The commented-out code in main() demonstrates this. This is the most concise and preferred approach if you have C++17 available. I've included the manual GCD/LCM functions as well, for instances where the C++17 library may not be available.
Error Handling (Consideration): For more robust code, you might want to add error handling to check if the user inputs valid integers. You can use std::cin.fail() to detect invalid input.
Nếu bạn muốn hỏi bài tập
Các câu hỏi của bạn luôn được giải đáp dưới 10 phút
CÂU HỎI LIÊN QUAN
Top thành viên trả lời