There is a Java program that is missing one recursive function: public class GCD { /* There is...

60.1K

Verified Solution

Question

Programming

There is a Java program that is missing one recursivefunction:

public class GCD {

/* There is a neat trick with recursive programming. Thefunction described

   * below requires that y is at most x. Rather thanadd this to the recursive

   * function definition, we can add a front-end,helper function.

   *

   * I wrote this function for you and I called itgcd. The recursive logic goes

   * in a function called gcd_rec. All gcd does ismake sure that x is not

   * smaller than y.    

   */

/* Requires x >= y

  *           /x           when y is 0

   * gcd(x,y) = |

   *           \gcd(y, x%y) otherwise

   */

public static int gcd_rec(int x, int y) {

    return 0;

}

public static int gcd(int x, int y) {

    if(x < y)

      return gcd_rec(y,x);

    else

      return gcd_rec(x,y);

}

/* Greatest Common Divisor Test Framework

   */

public static void main(String[] args) {

    int[] inputX = {10, 35, 14, 4181};

    int[] inputY = { 8, 15, 35, 6765};

    int[] expect = { 2, 5, 7,   1};

    boolean error = false;

    assert(inputY.length == inputX.length);

    for(int i = 0 ; i < inputX.length; i++){

      int answer = gcd(inputX[i],inputY[i]);

      if(answer != expect[i]) {

       System.out.printf(\"ERROR: gcd(%d,%d) returned %d not %d.\n\",

                         inputX[i], inputY[i], answer, expect[i]);

        error = true;

      }

    }

    if(error)

      System.exit(1);

    else

      System.out.println(\"GoodJob!\");

}

}

Answer & Explanation Solved by verified expert
4.1 Ratings (678 Votes)
The recursive function gcdrec can be written asfollowsThe inline comments are provided for the betterunderstanding of the program logic public static int gcdrecint x int y ify 0 Return x if y 0 This is the exit condition of the recursive function return x else If not call the gcdrec recursively by passsing in the parameters y x y x    See Answer
Get Answers to Unlimited Questions

Join us to gain access to millions of questions and expert answers. Enjoy exclusive benefits tailored just for you!

Membership Benefits:
  • Unlimited Question Access with detailed Answers
  • Zin AI - 3 Million Words
  • 10 Dall-E 3 Images
  • 20 Plot Generations
  • Conversation with Dialogue Memory
  • No Ads, Ever!
  • Access to Our Best AI Platform: Flex AI - Your personal assistant for all your inquiries!
Become a Member

Other questions asked by students