Hacker News new | ask | show | jobs
by untitledwiz 4624 days ago
Add them all up, subtract that from the actual sum of 1-250 and voila. Optimization bonus: you don't need to do the second sum, there's a closed form (I don't remember what it is, but I do remember Gauss came up with it as a kid).
4 comments

Doesn't this only work if you have spaces between the numbers?
no spaces.

but you can get the formula by imagining the numbers as piles of pennies and then completing them to make a square and then splitting down the diagonal

  *
  **
  ***

  *..
  **.
  ***

  \..   \
  *\. + \
  **\   \
where a \ is half a penny. so * = \\

so it's 1/2 * n * n (ie half the square) plus an extra 1/2 for each one on the diagonal.

so it's n * n/2 + n/2 = (n+1) * n/2

andrewcooke supposed the numbers were not separated by spaces so

1727321173475

could be 1, 72, 73, 211, ... or 17, 27, 32, 117, ... or 172, ...

n(n+1)/2