Hi everyone! In my Java class right now, we're doing iteration and recursion. One part of our assignment is to compute the Greatest Common Denominator in a small program -- both iteratively and recursively.
These are the specifications of the assignment:
-
public static long recursive (long a, lo. In this exercise, your task is to implement an algorithm recursively. The recursive definition is:ng b) - If either
a<0orb<0, then their GCD is the same as the GCD of their absolute values. - Otherwise, if
b==0, then their GCD isa. - Otherwise, their GCD is the GCD of
band the remainder ofaafter division byb, in that order.
- If either
public static long iterative (long a, lo. Now, examine the recursive definition above and determine how to re-implement it as a loop. Then, write that implementation in this method.ng b)
Now, I've written my code, and it compiles fine. However, I'm not quite sure if I'm coding it in the way the assignment wants, especially with this: "Otherwise, their GCD is the GCD of b and the remainder of a after division by b, in that order. " I'm also not quite sure if my program works well when tested with negative numbers. If you wouldn't mind, can you take a look at my code and tell me about any glitches in it? :) I would appreciate it so much! Thanks!
public class GCD {
public static long recursive(long a, long b){
long r;
r = a % b; // remainder variable
if (a < 0 || b < 0){
if (r == 0){
return Math.abs(b) ;
}else{
return recursive(b,r);
}
}else{
if (b==0){
return a;
}
if (r == 0){
return b;
}else{
return recursive(b, r);
}
}
}
public static long iterative(long a, long b){
long r; // remainder variable
//do-while statement
do {
r = a % b;
a = b;
b = r;
}while (r > 0);
return a;
}
}
I'm having a pretty hard time in Java. Was anyone else completly confused when first learning Java? What helped you master it?
