Menu driven program to find out the Greatest Common Divisor and Least Common Multiple of two numbers
#include<iostream>
#include<conio.h>
using namespace std;
int gcd(int first_number, int second_number);
int lcm(int first_number, int second_number);
int main()
{
int first_number = 0, second_number = 0, gc_number =
0, lc_number = 0, choice = 0;
cout
<< "\n\n\t\tGreatest Common Divisor OR
Least Common Factor";
cout
<< "\n\n\t\t\t 1. GCD (2 Numbers)\n\n\t\t\t 2. LCM (2 Numbers)";
cout << "\n\n\t\t\t 3. Exit";
cout << "\n\n\t\t\t 3. Exit";
cout
<< "\n\n\n\n\t\tEnter your choice ->
";
cin
>> choice;
switch(choice)
{
case 1:
cout
<< "\n\n
First Number - ";
cin
>> first_number;
cout
<< "\n\n
Second Number - ";
cin
>> second_number;
gc_number
= gcd(first_number, second_number);
cout
<< "\n\n
Greatest Common Divisor of " << first_number;
cout << " and " << second_number << " is " << gc_number;
cout << " and " << second_number << " is " << gc_number;
break;
case 2:
cout
<< "\n\n
First Number - ";
cin
>> first_number;
cout
<< "\n\n
Second Number - ";
cin
>> second_number;
lc_number
= lcm(first_number, second_number);
cout << "\n\n Least Common Multiple of " << first_number;
cout << " and " << second_number << " is " << lc_number;
break;
case 3: exit(1);
break;
default: cout << "\n\n\t
Inputted Choice is Wrong";
}
getch();
return 0;
}
int gcd(int first_number, int second_number)
{
int result = 0, counter = 0, smaller = 0;
if (first_number < second_number)
{
smaller
= first_number;
}
else
{
smaller
= second_number;
}
for(counter = 1; counter <= smaller; counter++)
{
if (((first_number % counter) == 0 ) &&
((second_number % counter) == 0))
{
result
= counter;
}
}
return result;
}
int lcm(int first_number, int second_number)
{
int result = 0, counter = 0;
for(counter = 1; counter <= first_number *
second_number; counter++)
{
if (((counter % first_number) == 0) &&
(((counter % second_number) == 0)))
{
result
= counter;
break;
}
}
return result;
}
Check out the links for the logics -
No comments:
Post a Comment