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.
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
# 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
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.
offers daily e-mail updates
news and tutorials
on topics such as: Data science
, Big Data, R jobs
, visualization (ggplot2
), programming (RStudio
, Web Scraping
) statistics (regression
, time series
) and more...
If you got this far, why not subscribe for updates
from the site? Choose your flavor: e-mail
, or facebook