GCD Calculator (Recursive & Non-Recursive)
Calculates the Greatest Common Divisor (GCD) of two numbers using both recursive and non-recursive methods.
#include <stdio.h>
int recgcd(int x, int y);
int nonrecgcd(int x, int y);
int main()
{
printf("INSTRUCTIONS: Enter two integers to calculate their GCD.\n");
int a, b, c, d;
printf("Enter two numbers a, b\n");
scanf("%d%d", &a, &b);
c = recgcd(a, b);
printf("The gcd of two numbers using recursion is %d\n", c);
d = nonrecgcd(a, b);
printf("The gcd of two numbers using nonrecursion is %d", d);
return 0;
}
int recgcd(int x, int y)
{
if(y == 0)
{
return(x);
}
else
{
return(recgcd(y, x % y));
}
}
int nonrecgcd(int x, int y)
{
int z;
while(x % y != 0)
{
z = x % y;
x = y;
y = z;
}
return(y);
}GCD Calculator (Recursive & Non-Recursive) — Free C Code Example
Calculates the Greatest Common Divisor (GCD) of two numbers using both recursive and non-recursive methods. This free code example is available in C and can be copied and run immediately — no account or signup required. Use the language tabs above to switch between implementations.
How to Use This Code
- Select your language — click the language tab (C, Java, C++, or Python) above the code viewer.
- Copy the code — use the copy button in the top-right corner of the code block.
- Run it — paste into a file with the correct extension (.c, .java, .cpp, .py), compile, and run using your terminal or IDE.
- Follow the on-screen instructions in the terminal to provide any required inputs.
Frequently Asked Questions
What does this program do?
Calculates the Greatest Common Divisor (GCD) of two numbers using both recursive and non-recursive methods.
Which languages is it available in?
Available in C. Switch between implementations using the tabs at the top of the code viewer.
How do I run this code?
Copy the code, save it with the right file extension (.c, .java, .cpp, or .py), then compile or run it with your installed compiler or interpreter (GCC, JDK, G++, Python 3).
Is this code free?
Yes — free to view, copy, and use. No account required.