I am trying to write a code to calculate the GCD (Greatest Common Divisor) of two numbers using recursion.
Although that I can print the common divisors of the numbers, I am struggling to print the GCD.
This is what I have to print the common divisors:
#include <stdio.h>
void gcd(int num1, int num2, int i) {
int x;
int small = (num1 < num2) ? num1 : num2;
if (i == small) {
return;
} else {
if (num1 % i == 0 && num2 % i == 0) {
x = i;
printf("%d ", x);
}
gcd(num1, num2, i + 1);
}
}
int main() {
int num1, num2, i;
printf("Enter the 1st number: ");
scanf("%d", &num1);
printf("Enter the 2nd number: ");
scanf("%d", &num2);
i = 1;
gcd(num1, num2, i);
return 0;
}
Now I have to print the GCD. But when I run the following program I get random outputs (address maybe). How do I solve this problem?
This is what I have so far to print the GCD:
#include <stdio.h>
void gcd(int num1, int num2, int i) {
int x;
int small = (num1 < num2) ? num1 : num2;
if (i == small) {
return;
} else {
if (num1 % i == 0 && num2 % i == 0) {
x = i;
}
gcd(num1, num2, i + 1);
}
printf("%d ", x);
}
int main() {
int num1, num2, i;
printf("Enter the 1st number: ");
scanf("%d", &num1);
printf("Enter the 2nd number: ");
scanf("%d", &num2);
i = 1;
gcd(num1, num2, i);
return 0;
}
The recursive implementation in C of GCD is (Euclid: around 300 BC):
I cannot guess where did you get what you write in your question. My apologies for it.