Javatpoint Logo
Javatpoint Logo

GCD of two numbers in C

In this topic, we will learn about GCD and find out different ways to get GCD of two numbers in C programming languages.

GCD of two numbers in C

The GCD is a mathematical term for the Greatest Common Divisor of two or more numbers. It is the Greatest common divisor that completely divides two or more numbers without leaving any remainder. Therefore, it is also known as the Highest Common Factor (HCF) of two numbers. For example, the GCD of two numbers, 20 and 28, is 4 because both 20 and 28 are completely divisible by 1, 2, 4 (the remainder is 0), and the largest positive number among the factors 1, 2, and 4 is 4. Similarly, the GCD of two numbers, 24 and 60, is 12.

GCD of two numbers using for loop

Let's consider a program to get the GCD of two numbers in C using for loop.

Gcd_for.c

Output

Enter any two numbers:
 96
36
 GCD of two numbers 96 and 36 is 12.

GCD of two numbers using while loop

Let's consider a program to get the GCD of two numbers in C using while loop.

Gcd_while.c

Output

GCD of two numbers 50 and 60 is 10.

Get the GCD of N numbers from the user

Let's consider a program to get the GCD of n numbers by taking the input from the users.

gcdNum.c

Output

GCD of two numbers 50 and 60 is 10.

Get the GCD of N numbers from the user

Let's consider a program to get the GCD of n numbers by taking the input from the users.

gcdNum.c

Output

Enter the N numbers from the users ( 0 to exists from the loop)
196
224
48
96
36
256
0

 GCD of all entered number is: 4

Get the GCD of two numbers using user defined function

Let's consider a program to get the GCD of two numbers using user defined function.

Func.c

Output

Enter the first number
96
 Enter the second number
 132
 GCD of the two numbers 96 and 132 is 12

GCD of two numbers using the modulo operator

Let's consider a program to find the GCD of two numbers using modulo operator.

Modulo.c

Output

Enter the first number:
 256
 Enter the second number:
 92
 GCD of two number 256 and 92 is 4

GCD of two numbers using Recursion

Let's consider a program to find the GCD of two numbers in C using Recursion.

Recursion.c

Output

Enter any two positive numbers:
60
48
GCD of two numbers 60 and 48 is 12

In the above program, the recursive function GCD_Rec() continuously calls itself until the value of num2 is equal to 0.

GCD of three numbers using if_else and for loop

Let's consider a program to get the GCD of three numbers in C using if else statement and for loop.

Gcd_num.c

Output

Enter any positive numbers:
 98
49
56
 GCD of three numbers 98, 49 and 56 is 7






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA