# Project Euler — problem 6

June 2, 2012
By

(This article was first published on Tony's bubble universe » R, and kindly contributed to R-bloggers)

It’s midnight officially. Let me solve the sixth problem before bed. This is a quick one.

The sum of the squares of the first ten natural numbers is, 12 + 22 + … + 102 = 385. The square of the sum of the first ten natural numbers is, (1 + 2 + … + 10)2 = 552 = 3025. Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 385 = 2640. Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

Well, this one is very simple. The problem is the solution itself, literally. The code is very straightforward: calculate the sum first, then one minus the other.

?View Code RSPLUS
 1 2 3 4  sum1 <- sum((1:100) ^ 2) sum2 <- (sum(1:100)) ^ 2 result <- sum2 - sum1 cat("The result is:", result, "\n")

Although the code above is straightforward, there is a simpler solution. We know that (1 + 2 + 3 + … + n) = (n)*(n+1)/2, so the square of the sum is easy to get. For the sum of the squares, you can solve a function f(n) = a*n3 + b*n2 + c*n + d, with f(0) = 0, f(1) = 1, f(2) = 5 and f(3) = 16. And the function is easily proven. As long as you get the values of a, b, c and d(btw, d = 0), you can use it to get the results very quickly. Here, the quick function is f(n) = 1/3*n3 + 1/2*n2 + 1/6*n.
PS: I think for any given power m, to calculate 1m + 2m + 3m + … + nm, there is always a quick function as f(n) = a1*nm+1 + a2*nm + a3*nm-1 + … + am+1*n. I already found f(n) = sum((1:n) ^ 3) = (n ^ 2) * (n + 1) ^ 2 / 4 and f(n) = sum((1:n) ^ 4) = n * (n + 1) * (2 * n + 1) * (3 * n ^ 2 + 3 * n - 1) / 30. Although it’s still a guess now, I think it’s very likely to be true. I just need a provement.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...