+92 332 4229 857 99ProjectIdeas@Gmail.com

Least Common Multiple-LCM (C++)


Least Common Multiple
Least Common Multiple (LCM) also called as Lowest Common Multiple or Smallest Common Multiple (SCM) of two or more integers, is the smallest positive integer that is a multiple of all numbers.

Code

#include "stdafx.h"
#include "conio.h"
#include "iostream"

using namespace std;

int gcd(int num1,int num2)
{     
       int temp1,temp2;

       if(num1<num2)
       {temp1=num1;num1=num2;num2=temp1;}

       if(num2==0)
              return num1;

       if(num1%num2==0)
              return num2;

       else
       { 
              while(num1%num2!=0)
              {
                     temp2=num1%num2;
                     num1=num2;
                     num2=temp2;
              }
     return temp2;
       }
return 0;
}

int lcm(int num1,int num2)
{
 return num1*num2/gcd(num1,num2);
}

int main()
{
       cout<<"LCM OF 56 & 42 is : " << lcm( 56 , 42 ) <<endl;
       cout<<"LCM OF 42 & 56 is : " << lcm( 42 , 56 ) <<endl;
       cout<<"LCM OF 10 & 20 is : " << lcm( 10 , 20 ) <<endl; 
       cout<<"LCM OF 18 & 99 is : " << lcm( 18 , 99 ) <<endl; 
       cout<<"LCM OF   0 & 42 is : " << lcm(  0 , 42 ) <<endl; 
       cout<<"LCM OF 56 &   0 is : " << lcm( 56 ,  0 ) <<endl; 

       _getche();
       return 0;
}

Output
LCM OF 56 & 42 is : 168
LCM OF 42 & 56 is : 168
LCM OF 10 & 20 is : 20
LCM OF 18 & 99 is : 198
LCM OF  0 & 42 is : 0
LCM OF 56 &  0 is : 0

0 comments: