If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In C language, you can use the Euclidean algorithm to find the greatest common divisor (GCD) of two numbers. The Euclidean algorithm is an efficient method for finding the GCD of two numbers. The basic idea of the algorithm is to repeatedly subtract the smaller number from the larger number until the two numbers become equal or the smaller number becomes zero. The GCD is then the remaining number.
Here's an example of C code that finds the GCD of two numbers using the Euclidean algorithm:
Copy code
#include <stdio.h>
int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
int main() {
int a, b;
printf("Enter two positive integers: ");
scanf("%d%d", &a, &b);
printf("The GCD of %d and %d is %d.\n", a, b, gcd(a, b));
return 0;
}
This code prompts the user to enter two positive integers, and then calls the gcd() function with those two numbers as arguments. The gcd() function uses a recursive approach to find the GCD of two numbers. It uses the modulus operator to check the remainder of a and b and call the function again with the b as first argument and remainder as the second argument. It continues to do this until b becomes zero. The number a is the GCD of two numbers. It is also possible to implement the GCD using a while loop and if statement to check the larger and smaller number and subtract the smaller number from the larger number until the smaller number becomes zero.
Comments: 0