Archive for category C or C++

GCD and LCM in CPP

Finding LCM of two numbers:

//CPP code for finding LCM of two numbers
#include<iostream.h>
#include<conio.h>

main()
{
clrscr();
int m, n;
cout<<“Enter first number:”;
cin>>m;
cout<<“Enter second number:”;
cin>>n;

int max;
int lcm=0;

if(m>n)
{
max=m;
}
else
{
max=n;
}

for(int i=max;i<=m*n;i++)
{
if(i%m==0 && i%n==0)
{
lcm=i;
break;
}

}
cout<<“LCM is:”<<lcm;
getch();
}

Finding GCD of two numbers:

//CPP code for finding GCD

#include<iostream.h>
#include<conio.h>

main()
{
clrscr();
int m, n;
cout<<“Enter first number:”;
cin>>m;
cout<<“Enter second number:”;
cin>>n;

int min;
int gcd;

if(m<n)
{
min=m;
}
else
{
min=n;
}

for(int i=1;i<=min;i++)
{
if(m%i==0 && n%i==0)
{
gcd=i;
}
}
cout<<“GCD is: “<<gcd;

cout<<endl;

cout<<“LCM is “<<m*n/gcd;

getch();
}

Advertisements

Leave a comment