Example 1: how to find hcf in c++
#include <iostream>
using namespace std;
int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
int main()
{
int a = 98, b = 56;
cout<<"GCD of "<<a<<" and "<<b<<" is "<<gcd(a, b);
return 0;
}
Example 2: gcd of two numbers c++
int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
int a = 105, b = 30;
cout<<"GCD of "<< a <<" and "<< b <<" is "<< gcd(a, b);
Example 3: gcd function in c++
int gcd(int a, int b)
{
if (a == 0)
return b;
if (b == 0)
return a;
if (a == b)
return a;
if (a > b)
return gcd(a-b, b);
return gcd(a, b-a);
}
Example 4: gcd in c++
#include<iostream>
using namespace std;
int euclid_gcd(int a, int b) {
if(a==0 || b==0) return 0;
int dividend = a;
int divisor = b;
while(divisor != 0){
int remainder = dividend%divisor;
dividend = divisor;
divisor = remainder;
}
return dividend;
}
int main()
{
cout<<euclid_gcd(0,7)<<endl;
cout<<euclid_gcd(55,78)<<endl;
cout<<euclid_gcd(105,350)<<endl;
cout<<euclid_gcd(350,105)<<endl;
return 0;
}
Example 5: gcd of two numbers in c
#include <stdio.h>
int main()
{
int n1, n2, i, gcd;
printf("Enter two integers: ");
scanf("%d %d", &n1, &n2);
for(i=1; i <= n1 && i <= n2; ++i)
{
if(n1%i==0 && n2%i==0)
gcd = i;
}
printf("G.C.D of %d and %d is %d", n1, n2, gcd);
return 0;
}
Example 6: gcd of two numbers in c
#include <stdio.h>
int main()
{
int n1, n2;
printf("Enter two positive integers: ");
scanf("%d %d",&n1,&n2);
while(n1!=n2)
{
if(n1 > n2)
n1 -= n2;
else
n2 -= n1;
}
printf("GCD = %d",n1);
return 0;
}