Cpp Examples Hcf Gcd
# C++ Example - Find the Greatest Common Divisor of Two Numbers
[ C++ Examples](#)
The user inputs two numbers, and the program finds their greatest common divisor.
## Example
#includeusing namespace std; int main(){int n1, n2; cout<>n1>>n2; while(n1 != n2){if(n1>n2)n1 -= n2; else n2 -= n1; }cout<<"HCF = "<<n1; return 0; }
The output of the above program is:
Enter two integers: 7852 HCF = 26
## Example
#includeusing namespace std; int main(){int n1, n2, hcf; cout<>n1>>n2; // Swap the variables if n2 is greater than n1 if(n2>n1){int temp = n2; n2 = n1; n1 = temp; }for(int i = 1; i<= n2; ++i){if(n1 % i == 0&&n2 % i ==0){hcf = i; }}cout<<"HCF = "<<hcf; return 0; }
The output of the above program is:
Enter two integers: 7852 HCF = 26
[ C++ Examples](#)
YouTip