Wednesday, 3 September 2014

Find out LCM and GCD using C++ programming

LCM-The least common multiple of two integers a and b, usually denoted by LCM(a, b), is the smallest positive integer that is divisible by both a and b.
Let’s write the program
#include<iostream>
using namespace std;
int fun(int ,int );
main()
{
    int a,b,k;
    cout<<"Enter your numbers : \n";
    cin>>a;
    cin>>b;
    k=fun(a,b);
    cout<<"Lowest common multiple is "<<k;

}
int fun(int a,int b)
  {
    int n;
    for(n=1;;n++)
    {
  if(n%a == 0 && n%b == 0)
   return n;
    }
  }
The output of above program
Enter your numbers :
4
5
Lowest common multiple is 20
GCD- The greatest common divisor of two positive integers a and b, usually denoted by GCD(a, b),is the largest divisor common to a and b.
Let’s write the program
#include<iostream>
using namespace std;
int fun(int ,int );
main()
{
    int a,b,k;
    cout<<"Enter your numbers : \n";
    cin>>a;
    cin>>b;
    k=fun(a,b);
    cout<<"Greatest Common Divisor is "<<k;

}
  int fun(int a,int b)
  {
    int c;
    while(1)
    {
  c = a%b;
  if(c==0)
   return b;
  a = b;
  b = c;
    }
  }
The output of above program
Enter your numbers :
40
35
Greatest Common Divisor is 5

0 comments:

Post a Comment