Problem overview
SumUntilLimit receives a positive int limit. You add the numbers 1, 2, 3, and so on, in that order, and stop as soon as the total is at least limit. The method returns how many numbers you added. The number that makes the total reach or pass the limit counts.
For limit = 10, 1 + 2 + 3 + 4 = 10 reaches the limit exactly, so the answer is 4. For limit = 11, the total after 4 numbers is 10, still below 11, so 5 is added too. The total becomes 15 and the answer is 5. For limit = 1, the first number is enough: the answer is 1.
Approach
Keep two variables: total, the sum so far, and count, how many numbers have been added. Because the numbers go 1, 2, 3 in order, count is also the last number added. So the next number to add is always count + 1.
The loop runs while total < limit. The moment the total reaches the limit, the condition is false and the adding stops. The condition is checked before each pass, so a pass that pushes the total over the limit still finishes, and its number is counted.
Step by step
- Create
totalas anintset to 0. Nothing has been added yet. - Create
countas anintset to 0. - Write
while (total < limit). The loop stops when the total is at least the limit. - Add 1 to
countwith++. It is now the next number: 1 on the first pass, 2 on the second. - Add
counttototal. The order of steps 4 and 5 matters:countgoes up first, so the number added is the next one in the sequence. - Return
countafter the loop.
For limit = 11:
| Pass | count | total |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 2 | 3 |
| 3 | 3 | 6 |
| 4 | 4 | 10 |
| 5 | 5 | 15 |
After pass 5, 15 < 11 is false, so the loop ends and the method returns 5.
The solution in C#
class Solution {
public int SumUntilLimit(int limit) {
int total = 0;
int count = 0;
while (total < limit) {
count++;
total += count;
}
return count;
}
}
The loop condition uses <, not <=. When total equals limit, the sum has reached the limit, which is the stop condition.
Why a loop and not a formula
The sum of the first k numbers has a closed form, k times (k + 1) divided by 2, so you could solve for k with a square root. A loop is simpler and avoids rounding questions. The condition total < limit says exactly what the problem says in words.
Edge cases and common mistakes
- Reaching the limit exactly. For
10the total hits 10 after 4 numbers and the loop stops there. - Overshooting. For
11, the total jumps from 10 to 15. The last number counts even though the total passes the limit. - Using
<=. It would add one extra number whenever the total lands exactly on the limit. - Swapped lines. If you add to
totalbefore incrementingcount, you add the previous number again and the sequence is shifted. - Largest input. For
1000000000, the loop runs 44721 times and the total ends a little above the limit, still within theintrange.
Testing
The solution returns 4 for 10, 5 for 11, 1 for 1 and 44721 for 1000000000.
