Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Difference between sum of the squares of and square of sum first n natural numbers.
Given a number n, find the difference between the square of the sum and the sum of the squares of the first n natural numbers. This is a classic mathematical problem that can be solved efficiently using direct formulas.
Formulas
The two formulas used are −
- Sum of squares of first n natural numbers: n(n+1)(2n+1) / 6
- Sum of first n natural numbers: n(n+1) / 2, then square it
The difference is: (Square of Sum) − (Sum of Squares).
Worked Example
For n = 3 −
Sum of squares = 1² + 2² + 3² = 1 + 4 + 9 = 14 Sum of numbers = 1 + 2 + 3 = 6 Square of sum = 6² = 36 Difference = 36 - 14 = 22
Java Implementation
The following program calculates the difference using the formulas ?
public class JavaTester {
public static int difference(int n) {
// sum of squares of n natural numbers
int sumSquareN = (n * (n + 1) * (2 * n + 1)) / 6;
// sum of n natural numbers
int sumN = (n * (n + 1)) / 2;
// square of sum of n natural numbers
int squareSumN = sumN * sumN;
// difference
return Math.abs(sumSquareN - squareSumN);
}
public static void main(String args[]) {
int n = 3;
System.out.println("Number: " + n);
System.out.println("Difference: " + difference(n));
n = 10;
System.out.println("Number: " + n);
System.out.println("Difference: " + difference(n));
}
}
The output of the above code is ?
Number: 3 Difference: 22 Number: 10 Difference: 2640
Conclusion
The difference between the square of the sum and the sum of squares can be computed in O(1) time using direct mathematical formulas, without needing loops. The square of the sum always grows faster than the sum of squares, so the difference increases rapidly with n.
Advertisements
