Counting steps · routine
Add up to n, instantly
Write sum_to(n) returning 1 + 2 + … + n — this time without a loop.
Pair the first number with the last: 1 + n, 2 + (n − 1), … Every pair adds up to n + 1, and there are n / 2 pairs.
- right answers
- arguments left as they should be
- fast enough at scale
- without sum
Run adds print(sum_to(100)) after your code, to try it.
Stuck on the idea rather than the code? The Counting steps lesson walks through it.