Euler Problem 6: Sum Square Difference
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Euler Problem 6 Definition
The sum of the squares of the first ten natural numbers is:
The square of the sum of the first ten natural numbers is:
The difference between the sum of the squares of the first ten natural numbers and the square of the sum is . Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
Solution
This is a straightforward problem for vector processing capabilities in R.
answer <- sum(1:100)^2-sum((1:100)^2)
This problem can also be solved arithmetically. When Carl Friedrich Gauss (1777-1855) when he was a child his teacher challenged his students to add all numbers from 1 to 100. All of his friends struggled to add all the 100 numbers one by one but Carl completed the task in a few seconds.
The same principle applies to computing. The first solution is like Carl’s classmates who slavishly add all numbers. This solution is based on arithmetic progressions.
The sum of natural numbers can be expressed as:
n <- 100 answer <- ((n*(n+1))/2)^2 - (n*(n+1)*(2*n+1))/6
The post Euler Problem 6: Sum Square Difference appeared first on The Devil is in the Data.
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.