English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Comprehensive Collection of C Programming Examples
Examples of calculating the GCD of two integers (positive and negative integers) in different ways using loops and decision statements.
To understand this example, you should understand the followingC programmingTopic:
The HCF or GCD (Greatest Common Divisor) of two integers is the largest integer that can exactly divide two numbers (without remainder).
There are many methods to find the GCD in C programming.
#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) { // Check if i is a factor of the two integers if(n1%i == 0 && n2%i == 0) gcd = i; } printf("G.C.D of %d and %d is %d", n1, n2, gcd); return 0; }
In this program, the two integers entered by the user are stored in the variable n1and n2in. Then loop for, until i is less than n1and n2.
In each iteration, if n1and n2can be divided by i, then assign the value of i to gcd.
When the for loop is completed, the GCD of the two numbers is stored in the variable gcd.
#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 -n =2; else n2 -n =1; } printf("Greatest Common Divisor = %d", n1); return 0; }
Output Result
Enter two positive integers: 81 153 Greatest Common Divisor = 9
This is a better way to find the GCD. In this method, subtract the smaller integer from the larger integer, and then assign the result to the variable that saves the larger integer. This process continues until n1and n2are equal.
Only when the user enters a positive integer can the above two programs work as expected. This is some modification of the second example, which can find the GCD of positive and negative integers.
#include <stdio.h> int main() { int n1, n2; printf("Enter two integers: "); scanf("%d %d",&n1&n2); // If the user enters a negative number, the sign of the number will be changed to positive n1 = ( n1 > 0) ? n1 : -n1; n2 = ( n2 > 0) ? n2 : -n2; while(n1!=n2) { if(n1 > n2) n1 -n =2; else n2 -n =1; } printf("Greatest Common Divisor = %d", n1); return 0; }
Output Result
Enter two integers: 81 -153 Greatest Common Divisor = 9
You can also useRecursion to Find Greatest Common Divisor.