Hey everyone, I recently had the assignment to write a recursive program to calculate greatest common denominator.
I barely understood recursion when our instructor explained it to us.
I understood how it works and calling on itself I am just bad at implementing it.
I think I almost got my program to run correctly. it does everything but print out the answer. It will take my two numbers but will not do anything after. Any help would be greatly appreciated.

``````import TerminalIO.KeyboardReader;

public class gcd
{
public static void main(String []args)
{

int gcd;
int a;
int b;
}
public static int gcd(int a, int b)
{
if(a > b)
return gcd(b, a % b);
else
return gcd(a, b % a);
}
}``````

Thanks

## All 8 Replies

well, you're not calling your method, and you have written no code to be performed after reading those two numbers.

what do you expect it to do?

also, in your recursive method, I think in one of the cases you should not call the method again, like this:

``````// return a if a is the smallest number
// if b is the smallest, make a recursive call to the method
public static int recursiveMethod(a, b){
if ( a < b )
return recursiveMethod(b, a);
return a;
}``````

Ok so trying to understand recursion better, what is different about what you did than me? and so are you saying I have no method to print my answer?

Also, the difference between my method and yours is, that in my method there will be either zero or one recursive calls, your method will call itself indefinetely.

Oh I see what you mean. I just need to figure out how to do that. Thanks

Hey everyone, I recently had the assignment to write a recursive program to calculate greatest common denominator.
I barely understood recursion when our instructor explained it to us.
I understood how it works and calling on itself I am just bad at implementing it.
I think I almost got my program to run correctly. it does everything but print out the answer. It will take my two numbers but will not do anything after. Any help would be greatly appreciated.

``````import TerminalIO.KeyboardReader;

public class gcd
{
public static void main(String []args)
{

int gcd;
int a;
int b;
}
public static int gcd(int a, int b)
{
if(a > b)
return gcd(b, a % b);
else
return gcd(a, b % a);
}
}``````

Thanks

well, it's best not to use the method call as a return statement, and have whether or not the method is recursively called depend on the value of an expression of an if statement, or another structure that 'll give the option to once reach an end, so that the correct value is returned.

I actually have all of these links open currently in separate tabs, thanks though

I think I got it now, thank you stultuske.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.