I'm having a hard time with this problem here:
Write a function named sumEvery5th that accepts a non-negative integer
n
and returns the sum of the integers divisible by 5 from 1 ton
, includingn
itself. Use afor
loop.
This is what I have so far:
var sumEvery5th = function(n){
let sum = 0;
for(let i = 1; n % 5 == 0; i++){
sum+ i
};
return sum;
}
I feel like I'm really close. Thanks for the help in advance.
You can start your loop at 5
, since 1, 2... are not divisible by 5. And instead of i++
, you can directly go 5 by 5, until i
is greater than n
:
var sumEvery5th = function(n) { let sum = 0; for (let i = 5; i <= n; i += 5) { sum += i; }; return sum; } console.log(sumEvery5th(10)); // 5 + 10 = 15 console.log(sumEvery5th(18)); // 5 + 10 + 15 = 30
Pure maths, no loop solution:
var sumEvery5th = function(n) { n = Math.floor(n / 5); return 5 * n * (n + 1) / 2; } console.log(sumEvery5th(10)); // 5 + 10 = 15 console.log(sumEvery5th(18)); console.log(sumEvery5th(20));
First I think you should understand how a for
loop works.
var sumEvery5th = function(n){
let sum = 0;
for(let i = 1; n % 5 == 0; i++){
sum+ i
};
return sum;
}
What you are doing, step by step, is:
i
with value 1.n
by 5 and taking the remainder value and comparing it with 0. In case it's true, you are skipping the code block inside the for and moving towards the return sum;
line.i
value. Usually your for
condition will depend in the variable declared in step 1. What you want to do is run the for
code block n
times. For that, you need to change your condition from n % 5 == 0
to i <= n
. This will make sure to run the code block while your i
is less or equal than n
, starting with a value of 1.
Now, inside your code block you add your divisible by 5
logic, checking against i
value.
for(let i = 1; i <= n; i++){
if (i%5 == 0) sum += i;
};
Now let's say I called sumEvery5th(5).
i
(1) is less than or equal n
(5).i
(2) is less than or equal n
(5). ...And so on, until i = 6, and in that case the code block is skipped and the program will continue its course. Ps.: There are ways to improve the performance of this algorithm, but now that you understand your for
loop a bit better I'll leave it to you:)
var sumEvery5th = function(n){
let sum = 0;
for(let i = 1; i <= n; i++){
if (i % 5 === 0) {
sum += i;
}
}
return sum;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.