Project Euler in R Problem 6
This is a short one which I suppose is good since I should be doing homework anyway!
Problem 6 of Project Euler asks us to find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
I took advantage of R’s elementwise vector multiplication to produce a nice 2line script:
1 2 

We can also take a more mathematical approach. It is a well known fact that the sum of the first “k” natural numbers is equal to k/2 * (k + 1). Also, the sum of the squares of the first “k” natural numbers is equal to k/6 * (k + 1) * (2k + 1). Both of these facts are very easily proven by induction.
Thus the difference between the sum of the squares of the first “k” natural numbers and the square of the sum can be expressed as:
(k/2 * (k + 1))^{2}  k/6 * (k + 1) * (2k + 1)
Plug in k = 100 to get the specific answer to this problem.