Deitel & Deitel, C How to Program 6th Edition, Exercise 5.29

/*5.29 (Greatest Common Divisor) The greatest common divisor (GCD) of two integers is the largest
integer that evenly divides each of the two numbers. Write function gcd that returns the greatest
common divisor of two integers.*/

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

int gcd(int, int);

int main() {
printf("%d\n", gcd(42,60));
return 0;
}

int gcd(int num1, int num2){
int g = 1, i;
if (num2 < num1) {
for (i = 2; i <= num2; i++) {
if (num1 % i == 0 && num2 % i == 0) {
g *= i;
num1 /= i;
num2 /= i;
i = 1;
}
}
return g;
}
for (i = 2; i <= num1; i++) {
if (num1 % i == 0 && num2 % i == 0) {
g *= i;
num1 /= i;
num2 /= i;
i = 1;
}
}
return g;
}

Comments

Popular posts from this blog

Deitel & Deitel, C How to Program 6th Edition, Exercise 6.23 (Turtle Graphics)

Deitel & Deitel, C How to Program 6th Edition, Exercise 6.22 (Total Sales)

Deitel & Deitel, C How to Program 6th Edition, Exercise 5.47 (Craps Game Modification)