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?