Apply Euclidean Algorithm
In this step, you will implement the Euclidean algorithm to find the Greatest Common Divisor (GCD) of two integers.
Open the previous gcd.c
file and modify it to include the GCD calculation:
cd ~/project
nano gcd.c
Update the code with the Euclidean algorithm implementation:
#include <stdio.h>
// Function to calculate GCD using Euclidean algorithm
int calculateGCD(int a, int b) {
// Ensure positive numbers
a = (a > 0) ? a : -a;
b = (b > 0) ? b : -b;
// Euclidean algorithm
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
int main() {
int num1, num2, gcd;
printf("Enter the first integer: ");
scanf("%d", &num1);
printf("Enter the second integer: ");
scanf("%d", &num2);
// Calculate GCD
gcd = calculateGCD(num1, num2);
printf("First number: %d\n", num1);
printf("Second number: %d\n", num2);
printf("Greatest Common Divisor: %d\n", gcd);
return 0;
}
Let's break down the Euclidean algorithm implementation:
- The algorithm repeatedly divides the larger number by the smaller number
- It uses the modulo operator
%
to get the remainder
- The process continues until the remainder becomes 0
- The last non-zero remainder is the GCD
Compile and run the program:
gcc gcd.c -o gcd
./gcd
Example output:
Enter the first integer: 48
Enter the second integer: 18
First number: 48
Second number: 18
Greatest Common Divisor: 6