Alok Menghrajani

Previously: security engineer at Square, co-author of HackLang, put the 's' in https at Facebook. Maker of CTFs.


This blog does not use any tracking cookies and does not serve any ads. Enjoy your anonymity; I have no idea who you are, where you came from, and where you are headed to. Let's dream of an Internet from times past.


Home | Contact me | Github | RSS feed | Consulting services | Tools & games

A classic problem in discete mathematics is finding the sum of the first n natural numbers: 1 + 2 + 3 + + n . This sum can also be written as: k = 1 n k

There are various ways to find the answer to this question. If you take a college level discrete mathematics class, you will learn various techniques. I'm going to give a quick overview of some of these techniques applied to this specific case.

Let's call the sum we are looking for Sn. The idea is to rewrite Sn as the sum from n to 1 and then add both equations. Each element of the sum will nicely pair up:

Sn= 1 + 2 + 3 + + n-2 + n-1 + n Sn= n + n-1 + n-2 + + 3 + 2 + 1 2Sn= 1+n + 2+n-1 + 3+n-2 + + n-2+3 + n-1+2 + n+1 = n+1 + n+1 + n+1 + + n+1 + n+1 + n+1

Which leads to: Sn=nn+12. It is believed that Gauss discovered this method when he was just 9 years old.

If you have some intuition about the result or want to prove that Gauss found the right answer, you can prove that the result is right by induction.

Let's prove that the solution is correct for n=1:

Sn=1= nn+12 =11+12 =1

And then let's prove that Sn is correct if Sn-1 is correct:

Sn=Sn-1+n =n-1n-1+12+n =nn+12 QED

We can express the idea behind the first method above by using a formal notation. We need to use 4 properties:

k K c ak = c k K ak

k K ak + bk = k K ak + k K bk

k K ak = pk K a pk Where p(k) is a permutation of k.

k = 0 n 1 = n + 1 (trivial to prove by induction)

We then have:

Sn = 0 k n k = 0 n-k n n-k = 0 k n n-k

And we can add the first and last sum:

2Sn = 0 k n k + 0 k n n-k = 0 k n n = n 0 k n 1 = n n+1

Let's define the sum of the square of every number from 1 to n:

Sn' = 1+2+4+ + n

We then have:

Sn' = k = 1 n k2 = k = 2 n+1 k-1 2 = k = 2 n k-1 2 + n2

Since the last sum is 0 for k=1, we can write:

k = 1 n k2 = k = 1 n k 2 - 2k + 1 + n2

We can cancel the k = 1 n k2 :

2 k = 1 n k = n + n2

Which leads to: Sn=nn+12

The repertoire method helps solve general forms of equations, e.g.:

S0= α Sn= Sn-1 +β+γn

This method works when the solution has the form:

Sn= Anα+ Bnβ+ Cnγ

We first set Sn=1:

1=α 1=1 +β+γn

α=1 β=0 γ=0

An=1


We then set Sn=n:

0=α n=n-1 +β+γn

α=0 β=1 γ=0

Bn=n


Finally, we set Sn=n2:

0=α n2= n-12 +β+γn 0=α n2= n2- 2n+ 1 +β+γn

α=0 β=-1 γ=2

-Bn+ 2Cn =n2


Which results in the general solution:

Sn= α+ nβ+ n2+n2 γ

Links