Image

Imagereuptake wrote in Imagejava_dev

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:

  1.  public static long recursive (long a, long b). In this exercise, your task is to implement an algorithm recursively. The recursive definition is:
    •  If either a<0 or b<0, then their GCD is the same as the GCD of their absolute values.
    • Otherwise, if b==0, then their GCD is a.
    • Otherwise, their GCD is the GCD of b and the remainder of a after division by b, in that order.
  2. public static long iterative (long a, long b). Now, examine the recursive definition above and determine how to re-implement it as a loop. Then, write that implementation in this method.

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?