Skip to main content

Practice · 1 of 4

Sum without the loop

CHALLENGE
Difficulty: beginner+25 XP

Implement sumTo(long n): return 1 + 2 + ... + n. A loop works for small n but the formula n * (n + 1) / 2 works for any n — use it (watch: n * (n + 1) can overflow int, use long).

Back to lesson: Practice: Algorithmic reasoning reps