minusSeven
minusSeven

Reputation: 234

Java : Method return

public class EulerProblem14 {

 int chainLength=1;
public int findChainLength(int number){
    System.out.println("number "+number);
    System.out.println("Chainlength  "+chainLength);

    if(number==1){
       System.out.println("the number is finally 1 return chain length");
       return chainLength;
    }
   if(number%2==0){
       chainLength++;
     return findChainLength(number/2);
   }
   else {
       chainLength++;
       findChainLength(number*3+1);
   }
   System.out.println("THIS SHOULD NOT BE EXECUTED");
   return -1;
}
public static void main(String args[]){

    System.out.println(new EulerProblem14().findChainLength(13));

}

While solving Project Euler Problem 14, I came across a weird problem in method return in java I never faced before . In the above method when the number is finally 1 it should return the count of a chain . But this is the output for input 13 .

number 13 Chainlength 1

number 40 Chainlength 2

number 20 Chainlength 3

number 10 Chainlength 4

number 5 Chainlength 5

number 16 Chainlength 6

number 8 Chainlength 7

number 4 Chainlength 8

number 2 Chainlength 9

number 1 Chainlength 10

the number is finally 1 return chain length

THIS SHOULD NOT BE EXECUTED

THIS SHOULD NOT BE EXECUTED

-1

The problem is in the last part when the number becomes 1 instead of returning chainlength = 10 it somehow skips it and executes code which should never be executed and returns -1 . It runs fine for all powers of 2 like 1,2,4,8 but fails for others .

This is probably a stupid mistake on my part . Nonetheless it is a problem for me .

Upvotes: 0

Views: 159

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499770

I haven't looked in detail, but I suspect this:

else {
    chainLength++;
    findChainLength(number*3+1);
}

should actually be:

else {
    chainLength++;
    return findChainLength(number*3+1);
}

You should then be able to remove the last two lines of the method entirely, as they're unreachable.

Upvotes: 9

Related Questions