+92 332 4229 857 99ProjectIdeas@Gmail.com

Greatest Common Divisor-GCD (C++)


Greatest Common Divisor (GCD)
Greatest Common Divisor (GCD) also known as Greatest Common Denominator, Greatest Common Factor (GCF) or Highest Common Factor (HCF) of two or more non-zero integers, is the largest positive integer that divides the numbers without a remainder.

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 main()
{
       cout << "GCD OF 42 & 56 is : " << gcd ( 42 , 56 ) << endl;
       cout << "GCD OF 56 & 42 is : " << gcd ( 56 , 42 ) << endl;
       cout << "GCD OF 42 & 42 is : " << gcd ( 42 , 42 ) << endl;
       cout << "GCD OF 10 & 20 is : " << gcd ( 10 , 20 ) << endl;
       cout << "GCD OF 11 & 99 is : " << gcd ( 11 , 99 ) << endl;
       cout << "GCD OF  8 & 12 is : " << gcd (  8 , 12 ) << endl;

       _getche();
       return 0;
}

Output
GCD OF 42 & 56 is : 14
GCD OF 56 & 42 is : 14
GCD OF 42 & 42 is : 42
GCD OF 10 & 20 is : 10
GCD OF 11 & 99 is : 11
GCD OF  8 & 12 is : 4

0 comments: