Sunday, January 25, 2015

Problem 006 : Sum Square Difference

Sum square difference

Problem 6

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.
                                                                                                           https://projecteuler.net/problem=6

Problem 6 is a really simple problem if you know how to use for loop.

However, just like problem 1, I used formula to solve this problem, instead of for loop.

The formula for the sum of first n integers is:

n * (n + 1) / 2

The formula for the sum of first n squares is:

n * (n + 1) * (2n + 1) / 6

Therefore, the sum of the squares is:

int sumsquare = (NUM*(NUM+1)*(2*NUM+1))/6; //sum of the squares

and the square of the sum is:

int squaresum = (int)Math.pow((NUM)*(NUM+1)/2, 2);  //square of the sum

Answer is 25164150
Execution time is 0.8 ms, or 0.0008 seconds

No comments:

Post a Comment