The most important part of solving a problem is to gather information.
- What is the problem? — In this case, the problem is that we are being passed a number into a function, but the function currently does not provide the desired output.
- What are we trying to achieve? — We want our function to take a number and then provide the sum of all the natural numbers below it, which are multiples of either 3 or 5.
Now the fun part…
- Create a variable to hold the sums
- Use a for loop to go through the numbers leading up
The for loop here starts with i = 0, continues looping until i = number, and i increments by +1 each loop. This lets us check each number leading up to the number that gets passed through the function.
- Check each number if it is a multiple of 3 or 5
Using an if statement, we can check if the current number, i, is divisible by 3 or 5 using the modulus operator. If the result of i % 3 or i % 5 is equal to 0 that would mean that there were no remainders and that it passes our check. Upon passing the check, we will add the number to our sum variable as shown by the commented area.
Notice that continue; was added after where we would add to the sum. We do this so that as soon as a number is added the first time that it would skip the other checks for that number. Otherwise, if a number was divisible by both 3 AND 5 it would have been added twice. The instructions stated that it should only be counted once in that case.
- Add the number to the sum if it passes the check
The last part was really the hardest part of this problem. It’s smooth sailing from here. As you can see we added sum+=i, which is the same as sum = sum + i.
- Return the sum
Did it work?
Now we check if our solution passes the tests!