# Project Euler: problem 6

[This article was first published on

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

**We think therefore we R**, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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 their blog:**We think therefore we R**.R-bloggers.com offers

**daily e-mail updates**about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.