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.
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
This code on GitHub.