Project Euler Problems 1 to 100 - Problem 1: Multiples of 3 and 5

My code isn’t working for some test cases:
My code is working for these test cases: 10, 49 and 1000
but it throws Maximum call stack size exceeded error message for these test cases: 8456, 19564
I have written a recursive function and it starts by subtracting 1 from the passed number because we don’t add 10 for multiples of 10 for example so i wanted it to start from a number that is 1 less than the number that is passed
My code checks if a number is divisible by 3 or by 5, if it is it adds every time the function is called else it calls the function again without adding.

My code so far

function multiplesOf3and5(number) {
  number = number-1;
  if(number <= 1){
    return 0;
  }
  else{
    return number%3 == 0 || number%5 == 0 ? multiplesOf3and5(number) + number: multiplesOf3and5(number);
  }
}

console.log(multiplesOf3and5(19564));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36 Edg/115.0.1901.203

Challenge: Project Euler Problems 1 to 100 - Problem 1: Multiples of 3 and 5

Link to the challenge:

Hey, what’s your question exactly? Do you have troubles with understanding what the error means or what might be needed to do about it?

what might need to do about it. I made the solution using a for loop but i wanted it to work using recursive function. i want to pass all the test cases but i already know what the error message means

This might sound a bit obvious, but the only way to make recursive function to work here is reducing the number of function call. Otherwise, with high numbers the stack limit will be exceeded.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.