**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, 1

^{2}+ 2^{2}+ … + 10^{2}= 385. The square of the sum of the first ten natural numbers is, (1 + 2 + … + 10)^{2}= 55^{2}= 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*n^{3} + b*n^{2} + 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*n^{3} + 1/2*n^{2} + 1/6*n.

PS: I think for any given power m, to calculate 1^{m} + 2^{m} + 3^{m} + … + n^{m}, there is always a quick function as f(n) = a_{1}*n^{m+1} + a_{2}*n^{m} + a_{3}*n^{m-1} + … + a_{m+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.

**leave a comment**for the author, please follow the link and comment on their blog:

**Tony's bubble universe » R**.

R-bloggers.com offers

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