answersLogoWhite

0

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;

}

User Avatar

Wiki User

15y ago

Still curious? Ask our experts.

Chat with our AI personalities

BlakeBlake
As your older brother, I've been where you are—maybe not exactly, but close enough.
Chat with Blake
CoachCoach
Success isn't just about winning—it's about vision, patience, and playing the long game.
Chat with Coach
TaigaTaiga
Every great hero faces trials, and you—yes, YOU—are no exception!
Chat with Taiga

Add your answer:

Earn +20 pts
Q: Write a C program to find GCD of 2 numbers using non-recursion?
Write your answer...
Submit
Still have questions?
magnify glass
imp