Program to Find GCD, examples of different ways to calculate GCD of two integers (for both positive and negative integers) using loops and decision making statements.
To understand this example to Find GCD, you should have the knowledge of following C++ programming topics:
- C++ if, if…else and Nested if…else
- C++ for Loop
- C++ while and do…while Loop
The largest integer which can perfectly divide two integers is known as GCD or HCF of those two numbers.
Program to Find GCD using the while loop
#include <iostream> using namespace std; int main() { int n1, n2; cout << "Enter two numbers: "; cin >> n1 >> n2; while(n1 != n2) { if(n1 > n2) n1 -= n2; else n2 -= n1; } cout << "HCF = " << n1; return 0; }
Output
Enter two numbers: 78 52 HCF = 26
In the above program, a smaller number is subtracted from the larger number and that number is stored in place of the larger number.
This process is continued until two numbers become equal which will be HCF.
Program to Find HCF/GCD using for loop
#include<iostream> using namespace std; int main() { int first_number; cout<<"Enter First Number : "; cin>>first_number; int second_number; cout<<"Enter Second Number: "; cin>>second_number; int gcd; for (int i=1;i<=first_number&&i<=second_number;i++){ if (first_number%i==0 && second_number%i == 0 ){ gcd=i; } } cout<<"Greatest Common Divison (GCD):"<<gcd<<endl; return 0; }
Output
Enter First Number : 1 Enter Second Number: 5 Greatest Common Divison (GCD):1
The logic of this program is simple.
In this program, the small integer between n1 and n2 is stored in n2. Then the loop is iterated from i = 1 to i <= n2 and in each iteration, the value of i is increased by 1.
If both numbers are divisible by i then, that number is stored in variable hcf.
When the iteration is finished, HCF will be stored in variable hcf.
Related Programs
- C++ Program to display factors of a Number.
- C++ Program to check whether a number is a Palindrome or Not.
- C++ Program to display Prime Number Between two intervals.
- C++ Program to check Amstrong Number.
- C++ Programs To Create a Pyramid and Pattern
- C++ Program to Check Whether a Number is Prime or Not
- C++ Program to display Amstrong Number between Two intervals.
- C++ Program to create a Pyramid and Pattern.
Ask your questions and clarify your/others doubts on C++ Selection Sort Program by commenting. Documentation.