문제

I'm attempting to add all the multiples of 3 or 5 under 1000 using a recursive method.

Here's my code

public static void main(String args[]){

    //TODO: Find all the multiples of 3 or 5 below 1000

    //Functional


    System.out.println(addMultiples(1, 0));


    /*

    //Imperative solution

    int num = 0;

    for(int i = 1; i < 1000; i++){
        if(i % 3 == 0 || i % 5 == 0){
            System.out.println(i + " is a multiple of 3 or 5.");
            num += i;
        }
    }
    System.out.printf("The sum of all the multiples of 3 or 5 below 1000 is %d", num);
    */

}

public static int addMultiples(int num, int base){

    //Exit case
    if (num >= 1000)
        return base;
    else if (num % 3 == 0 || num % 5 == 0) 
        base += num;


    addMultiples(++num, base);

    //I was forced to return a  -1. Compiler said. :(
    return -1;
}

Why is this code returning a -1? It's clear that if num >= 1000, the recursion would stop. I tried putting a System.out.println(base) inside my exit condition and it was printing out the number that I wanted.

Also, why did the compiler tell me to return a -1?

도움이 되었습니까?

해결책

Eventually the base case does get called and it returns base, whatever that is. But all calls below it in the stack ignore it and return -1.

Just have the recursive case return whatever the recursive call returns:

return addMultiples(++num, base);

다른 팁

The answer is simple. Replace the following code

addMultiples(++num, base);
return -1;

with this:

return addMultiples(++num, base);

What you're doing in your code is that you are simply invoking the recursive method again and discarding its return value, and returning -1 if the base case is not satisfied. In the new code, you're actually using the return value and properly invoking the recursive method.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top