Write a C program to find GCD of 2 numbers using non-recursion?

1 answer

Answer

1049581

2026-04-30 18:45

+ Follow

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;

}

ReportLike(0ShareFavorite

Copyright © 2026 eLLeNow.com All Rights Reserved.