Question:
Write a function sumMultiples taking a natural number n and returning the sum of all multiples of 3 and of 5 that are truly less than n.
Example: All multiples of 3 and 5 less than 20 are 3, 5, 6, 9, 10, 12, 15 and 18. Their sum is 78. sumMultiples(20) should return 78.
Answer:
function sumMultiples (n) {
let sum = 0;
for (let i = 1; i < n; i++) {
if (i % 3 === 0 || i % 5 === 0) {sum += i;}
}
return sum;
};
> we declare a function 'sumMultiples'
> it has one parameter 'n'
> we declare a variable 'sum'
> we initialize it with a value of '0'
> we open a 'for loop'
> this loop will use all the numbers below 'n' to check for our conditions
> we open an 'if' statement that will have to meet any one of the two conditions to execute the code in its block
> the 'for loop' will only add the number to the 'sum' if it is a multiple of 3 or 5
> it will not add any number to the sum if there are no multiples of 3 and 5
> once the for loop has met its terminating condition then we simply return the 'sum'
No comments:
Post a Comment