0

I am a fresh student in computer science and currently we study Java recursion. Unfortunately, the academy only explains the following regarding this topic:

  1. What recursion means.
  2. There are 2 types of cases when using a recursive algorithm: base cases and recursive cases and their purpose.
  3. An example of factorial and Fibonacci implementation using recursion.

Now I got the following exercise:

Two integer numbers will be called "strangers" if their greatest common divisor (aka GTC) is ONLY 1". For example, the numbers 8 and 9 are "strangers" because their GTC is 1. However, 8 and 9 are not "strangers" because their GTC is 2.

Please implement a recursive method which receives an array of integers, and returns "true" if every pair numbers in this array are strangers, and "false" otherwise.

Method signature must be as follows:

public boolean checkGCD(int[] values)

For example:

{3, 5, 7, 11} -> method will returns true.
{4, 7, 8, 9} -> method will returns false because 4 and 8 are not strangers.

For assistance, you can use the following method for finding GTC (Euclidean algorithm):

private static int gcd(int n, int m){
    if (m==0) 
    return n;

    return gcd(m,n % m);
}

In addition, the method checkGCD(int[] values) should be overloaded...

Loops cannot be used!

The above can be done very easily with a nested loop, but I must use recursion!

I understand that I need to use an overloaded method which gets the array, lo index and hi index.

So this is what I came up in mind:

@@@@@@

Base case: if there is at least one pair of numbers in the array which are not strangers, method returns false (no need to continue the comparison...).

@@@@@@

Comparison will be done in the following way: lo index points to the 1st cell -> hi index points to the 2nd cell -> comparing -> hi index is incremented by 1 until it reaches the last cell of the array.

Then, lo index is incremented by 1, and then repeating the above.

So bottom line, I should compare the first cell to all consecutive cells, compare the 2nd to all consecutive cells, the 3rd etc...

@@@@@@@@

If all pairs of numbers are strangers, I need something else to stop recursion. Therefore, if all pairs are strangers, it means that lo index and hi index will eventually point to the last cell (cause both lo and hi index has incremented gradually, and they reach the last array cell after all comparisons turned out to be OK i.e strangers).

The following is the overloaded function:

   private static boolean checkGCD(int[] values, int lo, int hi)
    {

        if ( (gcd(values[lo], values[hi]) )!= 1 )
            return false;

        else if (lo < values.length-1 && hi < values.length-1)
                return checkGCD(values, lo, hi+1);
        else if (lo < values.length-2 && hi == values.length-1)
                return checkGCD (values, lo+1, lo+2);

        if (lo == values.length-1 && hi == values.length-1)
            return true;

         } -> Compiler says "missing return statement"**

The following is the method the exercise requires to have, and it basically just calls the overloaded method which does everything recursively.

 public static boolean checkGCD(int[] values)
  {
      return checkGCD(values, 0, 1);      
  }

When I try to compile, I get "missing return statement" which points to the close bracket in the overloaded function

But I do use "return" in the overloaded function.

Please clarify how to fix. I am sure after compilation error, the above overloaded function is still not OK.

6
  • This question appears to be off-topic because it is about Homework. Commented Mar 21, 2014 at 13:49
  • 1
    The title must to describe the problem >> stackoverflow.com/help Commented Mar 21, 2014 at 13:50
  • 4
    @LutzHorn: homework questions are not off-topic. Non-specific, overly broad questions are off-topic, but this does not seem to apply in this case. Commented Mar 21, 2014 at 13:51
  • 1
    So 8 and 9 are strangers, but they are also NOT strangers? That doesn't sound right... Commented Mar 21, 2014 at 13:52
  • 1
    Hi, with all due respect, I am trying to understand how recursion works, the exercise is just the tool. I am not concerned about the solution. Please advise. Commented Mar 21, 2014 at 13:53

5 Answers 5

3

You get the compiler error because, if every if fails, the method does not return anything. The solution is add the appropriate return statement when the final if fails.

Sign up to request clarification or add additional context in comments.

Comments

2

Not to give the answer away, but here's a strong hint: the base case is an array with two elements. All larger arrays are recursive cases.

1 Comment

Or the base case is an empty list; implementer's choice.
0

There's a general pattern for going through a list with a recursion (pseudocode):

 Result f(List f) {
      if(f is an empty list) {
          return Result for an empty list;
      } else {
          return (Result for head of list) merged with f(tail of list)
      }
 }

Since you're using arrays, rather than a type with convenient head() and tail() methods, you could pass in an index to say how much of the array you want to process. When index == array.length you are processing an "empty list".

 boolean allMembersPositive(int[] array, int index) {
     if(index == array.length) {
          return true;
     } else {
          return (array[index] >=0) && (allMembersPositive(index + 1));
     }
 }

It's a small step to adapt this to consume two array items per recursive call.

Comments

0

I can guarantee you that when you understand recursion clearly you are going to level up your programming skills.

I recommend reading these URLs:

http://howtoprogramwithjava.com/java-recursion/

http://danzig.jct.ac.il/java_class/recursion.html

Now, lets move back to your questions. I think that is one possible way to implement it:

public class Test {

    public static void main(String[] arguments) {
    int[] strangers = { 3, 5, 7, 11 };
    int[] acquaintances = { 4, 7, 8, 9};

    boolean verifyStrangers = checkGCD(strangers);
    boolean verifyAcquaintances = checkGCD(acquaintances);

    System.out.println(verifyStrangers);
    System.out.println(verifyAcquaintances);

    }

    public static boolean checkGCD(int[] values) {
    return checkGCD(values, 0, 1);
    }

    /*
     * I'm really not sure why your professor wants this method signature: "checkGCD(int[] values, int i, int j)"
     * I'm coding what I understood from the problem.
     */
    private static boolean checkGCD(int[] values, int i, int j) {
    boolean result = true;
    if (gcd(values[i], values[j]) != 1){
        result = false;
    }
    j++;
    if (j < values.length ) {
        result = result && checkGCD(values, i, j);
    }
    return result;
    }


    private static int gcd(int n, int m) {
    if (m == 0)
        return n;
    return gcd(m, n % m);
    }

}

Comments

0

I managed to solve the exercise.

    public static int gcd(int n, int m)
    {
           if (m==0) 
            return n;

            return gcd(m,n % m);
    }


    private static boolean checkGCD(int[] values, int lo, int hi)
    {

  //      System.out.println("lo is " + lo + " hi is " + hi);
  //      System.out.println("");

  //      System.out.println("[lo] is " + values [lo] + " [hi] is " + values[hi]);
  //      System.out.println("");

        if ( (gcd(values[lo], values[hi]) )!= 1 )
            return false;

        if (lo < values.length-1 && hi < values.length-1)
                return checkGCD(values, lo, hi+1);

        if (lo < values.length-2 && hi == values.length-1)
            return checkGCD(values, lo+1, lo+2);

        if (lo == values.length-2 && hi == values.length-1)
          return true;  

          return true; 

    }


  public static boolean checkGCD(int[] values)
  {
      return checkGCD(values, 0, 1);      
  }

:-)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.