(This article was first published on

**We think therefore we R**, and kindly contributed to R-bloggers)The sum of the squares of the first ten natural numbers is,

1

^{2}+ 2^{2}+ … + 10^{2}= 385The square of the sum of the first ten natural numbers is,

(1 + 2 + … + 10)

^{2}= 55^{2}= 3025Hence 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.

This is one quite simple.

# Create a vector with the first hundred natural numbers

x.1 <- (1:100)

# Square each element of the vector of natural numbers, i.e, square each natural number and store in another vector

y.1 <- x.1^2

head(y.1)

# Sum the first hundred natural numbers and the squares of each of the first hundred natural numbers and take the difference of these sums

a.1 <- sum(y.1)

b.1 <- (sum(x.1))^2

b.1 – a.1

b.1

Answer: 25164150

After solving a couple of these problems, andafter reading some solutions posted by aatrujillo here and here, I realize that my solutions are notgeneral, i.e., they only cater to the problem at hand and hence their scope isvery limited. For example, consider the above problem. Had the question askedto do the same analysis on the first 200 natural numbers, I would have torewrite the entire loop again. I understand that in this case it does notinvolve much more than changing the size of the x.1 vector, but for a problemthat involves more than one loop, it seems to be very “uncool”. As aresult, I have decided to orient my results towards general solutions and thensolve the problem by specifying the parameters. Let’s see how that goes.

To

**leave a comment**for the author, please follow the link and comment on his blog:**We think therefore we R**.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...