0% found this document useful (0 votes)
4 views3 pages

ALOJADO - FERNANDEZ - LONTOK - Final Laboratory Activity#3 - Functions

This C++ program calculates the Greatest Common Divisor (GCD), Least Common Multiple (LCM), and common divisors of two positive integers input by the user. It includes input validation to ensure that the numbers entered are positive integers. The program outputs the GCD, LCM, and lists the common divisors of the two numbers.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views3 pages

ALOJADO - FERNANDEZ - LONTOK - Final Laboratory Activity#3 - Functions

This C++ program calculates the Greatest Common Divisor (GCD), Least Common Multiple (LCM), and common divisors of two positive integers input by the user. It includes input validation to ensure that the numbers entered are positive integers. The program outputs the GCD, LCM, and lists the common divisors of the two numbers.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

#include <iostream>

#include <limits>
using namespace std;

int gcd(int a, int b) {


while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}

int lcm(int a, int b) {


return (a / gcd(a, b)) * b;
}

void commonDivisors(int a, int b) {


int divisor = gcd(a, b);
cout << "The Common Divisors of " << a << " and " << b << " are: ";
for (int i = 1; i <= divisor; i++) {
if (a % i == 0 && b % i == 0) {
cout << i << " ";
}
}
cout << endl;
}

bool isValidInput(int num) {


if (cin.fail() || num <= 0) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
return false;
}
return true;
}

int main() {
int num1, num2;

cout << "WELCOME!\n";


cout << "This program will compute for the following:\n";
cout << "1. Greatest Common Divisor (GCD)\n";
cout << "2. Least Common Multiple (LCM)\n";
cout << "3. Common Divisors\n\n";

cout << "Enter the first number: ";


cin >> num1;
if (!isValidInput(num1)) {
cout << "Invalid input! Please enter a positive integer.\n";
return 1;
}

cout << "Enter the second number: ";


cin >> num2;
if (!isValidInput(num2)) {
cout << "Invalid input! Please enter a positive integer.\n";
return 1;
}

int gcdResult = gcd(num1, num2);


int lcmResult = lcm(num1, num2);

cout << "\nThe Greatest Common Factor (GCF) of " << num1 << " and " << num2 << " is: " << gcdResult
<< endl;
cout << "The Least Common Multiple (LCM) of " << num1 << " and " << num2 << " is: " << lcmResult <<
endl;
commonDivisors(num1, num2);

return 0;
}

You might also like