DSA Factory
Free lessonsProgramming basics · Stage 3 · Loops that count · Step 4

Jumps and countdowns

Make a loop skip ahead by more than one, or count backwards. About 8 minutes.

Jumping ahead

A loop doesn't have to go up by one. Think of climbing a staircase two steps at a time, or reading every fifth page of a book.

A range can take a third number, the size of each jump. In Python, range(2, 11, 3) starts at 2 and adds 3 each time, so it gives 2, 5 and 8. The next would be 11, which is past the end. The other languages write this inside the for line, as the part that says what happens after each pass.

The third number: is how far the counter jumps each pass.
In code
for i in range(2, 11, 3):
    ...    # i is 2, then 5, then 8
Every 4th number up to 12
1
0
2
1
3
2
4
3
5
4
6
5
7
6
8
7
9
8
10
9
11
10
12
11
i
i
4
total
4

The loop starts at 4 and jumps by 4 each pass. The first i is 4, and the total is 4.

Move 1 of 4

Counting down

Give the range a negative jump, and the counter walks backwards. A rocket countdown goes 10, 9, 8 and all the way to 1.

When you count down, the start is the big number and the stop is the small one. And as always, the stop number itself is left out, so to reach 1, stop at 0. You can also jump by more than one while counting down, such as counting down by 2.

Counting down? Start high, stop low, and use a negative jump.
In code
for i in range(10, 0, -2):
    ...    # 10, 8, 6, 4, 2
Quick check

Which values does range(1, 10, 3) take?

  1. A1, 4 and 7
  2. B1, 4, 7 and 10
  3. C3, 6 and 9
Show the answer

1, 4 and 7. Start at 1 and add 3 each time: 1, 4, 7. The next would be 10, but the end value is not included.

Your problem

Every k-th number

Return the sum of every k-th number from k up to n: k, 2k, 3k and so on, as long as they don't go past n. The sum can be large, so the result is a long.

Example
n = 12, k = 4 → 24

0 ≤ n ≤ 1,000,000 · 1 ≤ k ≤ 1,000,000

Solve it in your browserPython, C++, Java or JavaScript. Hints if you get stuck. No sign-up needed.
Start coding