One way to find the GCD (Greatest Common Divisor) of two numbers is Euclid's method. The following program demostrates this, without using recursion. The third number printed is the GCD of the first two. The highlighted lines are the core of the algorithm.
#include
int GcdByEuclid (int a, int b) {
if (a < 0 b < 0) return -1;
while (a > 0 && b > 0) if (a > b) a -= b; else b -= a;
if (a == 0) return b; else return a;
}
int main (int argc, char *argv[]) {
int a, b;
if (argc < 3) {
fprintf (stderr, "Usage: gcd a b\n");
return 1;
}
a = atoi(argv[1]);
b = atoi(argv[2]);
printf ("%d %d %d", a, b, GcdByEuclid (a, b));
return 0;
}
Chat with our AI personalities
To write a C++ program to display the student details using class and array of object.
12
write a vb program to find the magic square
Write and run a client and a server program in C-language using UDP
write a c++ program to convert binary number to decimal number by using while statement