Project Euler : Problem 6 - Sum square difference

1 minute read

Problem Statement : Sum square difference

Problem 6 : The sum of the squares of the first ten natural numbers is,

The square of the sum of the first ten natural numbers is,

Hence 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.

Concept and Theory

The sum of square of first terms of natural number is given as follows,

And sum of first terms of natural number is given as follows,

We are asked,

Code

/**
 * A function that calculates the absolute difference between the sum of the
 * squares of the first natural numbers and the square of the sum.
 *
 * @param num
 *            : the last number in the series
 *
 * @return result
 */
public static long sumSquareDifference(long num) {
  long result = (num * (num - 1) * (num + 1) * (3 * num + 2)) / 12;
  return result;
}

Test Your Skills

Wanna try a harder version of the above problem ? Check this HackerRank problem.

Solution

The solution will remain same as above method , you just need to call it for each test case.

References and Further Readings

Leave a Comment

Your email address will not be published. Required fields are marked *

Loading...