- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Difference between sum of the squares of and square of sum first n natural numbers.

## Problem Statement

With a given number n, write a program to find the difference between sum of the squares of and square of sum first n natural numbers.

## Example

n = 3 Squares of first three numbers = 3x3 + 2x2 + 1x1 = 9 + 4 + 1 = 14 Squares of sum of first three numbers = (3 + 2 + 1)x(3 + 2 + 1) = 6x6 = 36 Difference = 36 - 14 = 22

## Example

Following is the program in Java to find the required difference.

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)); } }

## Output

Number : 3 Difference: 22

- Related Articles
- Sum of square-sums of first n natural numbers
- Python Program for Sum of squares of first n natural numbers
- C++ Program for Sum of squares of first n natural numbers?
- Sum of squares of first n natural numbers in C Program?
- Java Program to calculate Sum of squares of first n natural numbers
- Sum of sum of first n natural numbers in C++
- PHP program to calculate the sum of square of first n natural numbers
- Sum of square of first n odd numbers
- Find the sum of first $n$ odd natural numbers.
- Sum of squares of the first n even numbers in C Program
- Sum of first n natural numbers in C Program
- Python Program for cube sum of first n natural numbers
- C Program for cube sum of first n natural numbers?
- C++ Program for cube sum of first n natural numbers?
- Java Program to cube sum of first n natural numbers

Advertisements