Hacker News new | past | comments | ask | show | jobs | submit login

My favorite off by one error is that the index of a count down is always one less than the amount that you subtracted. This means if you count up and down at the same time, you won’t count the middle number twice.

1: 1, 10 :0

2: 2, 9 :-1

3: 3, 8 :-2

4: 4, 7 :-3

5: 5, 6 :-4

Since the sum on each line is 11, the sum of all the numbers from one to ten is 55.

The cool thing is that this generalizes

1: 1, N : 0

2: 2, N - 1 :-1

3: 3, N - 2 :-2 <-sum is N+1

N/2: N/2, N -(N/2)+1 => N/2+1

So the sum of N numbers is N/2 * (N/2+N/2+1) => N/2 * (N+1) if N is even.

It appears to be broken for odd numbers

1: 1, 9 :0

2: 2, 8 :-1

3: 3, 7 :-2

4: 4, 6 :-3

5: 5, 0 :-4 <- can’t reuse 5

But for odds, setting the odd number K equal to N+1, N is an even number so the total sum is sum(N) + N+1. We showed that sum(N) = N/2 *(N+1). So we have N/2 * (N+1) + (N+1).

But that means N/2+1 * (N+1) equals sum(K)

=> (N+2)/2 * (N+1)

=> (K+1)/2 * K

So the formula N/2 * (N+1) computes the sum of N numbers if N is odd too! It works for all numbers. Wow!

[Edit: Formatting]




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: