Tuesday, October 03, 2006

Summing Consecutive Integers


A neat fact is that the sum of integers from 1 to N is equal to N * (N+1) / 2.
 
So, for example, 1+2+3+4+5 is equal to 5*6/2, which is 15.
 
This fact is really useful if you want to sum huge strings of consecutive numbers, because no matter how many numbers you have, this formula will give you the answer in one calculation.
 
So, if you actually added up the integers from 1 to 10,000 it would require 10,000 additions.  But, you can easily calculate the sum with one calculation: 10000*10001 / 2. which equals 50,005,000.
 
Thus, a programmer who codes the formula, instead of using brute force addition, would create a program that would run instantaneously, even for adding up millions of integers.


Here is an awk script for summing the integers, which I posted on my unix blog.

0 comments: