# Sum of squares of first n natural numbers

Last Updated : 13 Apr, 2023

Given n, find sum of squares of first n natural numbers.
Examples :

```Input : n = 2
Output : 5
Explanation: 1^2+2^2 = 5

Input : n = 8
Output : 204
Explanation :
1^2 + 2^2 + 3^2 + 4^2 + 5^2 + 6^2 + 7^2 + 8^2 = 204 ```

Naive approach :
A naive approach will be to run a loop from 1 to n and sum up all the squares.

## C

 `// C program to calculate` `// 1^2+2^2+3^2+...` `#include ` ` `  `// Function to calculate sum` `int` `summation(``int` `n)` `{` `    ``int` `sum = 0;` `    ``for` `(``int` `i = 1; i <= n; i++)` `        ``sum += (i * i);` `    ``return` `sum;` `}` ` `  `// Driver code` `int` `main()` `{` `    ``int` `n = 2;` `    ``printf``(``"%d"``,summation(n));` `    ``return` `0;` `}`

## C++

 `// CPP program to calculate` `// 1^2+2^2+3^2+...` `#include ` `using` `namespace` `std;`   `// Function to calculate sum` `int` `summation(``int` `n)` `{` `    ``int` `sum = 0;` `    ``for` `(``int` `i = 1; i <= n; i++)` `        ``sum += (i * i);`   `    ``return` `sum;` `}`   `// Driver code` `int` `main()` `{` `    ``int` `n = 2;` `    ``cout << summation(n);` `    ``return` `0;` `}`

## Java

 `// Java program to calculate` `// 1^2+2^2+3^2+...` `import` `java.util.*;` `import` `java.lang.*;`   `class` `GFG ` `{` `    ``// Function to calculate sum` `    ``public` `static` `int` `summation(``int` `n)` `    ``{` `        ``int` `sum = ``0``;` `        ``for` `(``int` `i = ``1``; i <= n; i++)` `            ``sum += (i * i);`   `        ``return` `sum;` `    ``}`   `    ``// Driver code` `    ``public` `static` `void` `main(String args[])` `    ``{` `        ``int` `n = ``2``;` `        ``System.out.println(summation(n));` `    ``}` `}`   `// This code is contributed ` `// by Sachin Bisht`

## Python3

 `# Python3 program to ` `# calculate 1 ^ 2 + 2 ^ 2 + 3 ^ 2+..`   `# Function to calculate series` `def` `summation(n):` `    ``return` `sum``([i``*``*``2` `for` `i ``in` `               ``range``(``1``, n ``+` `1``)])`   `# Driver Code ` `if` `__name__ ``=``=` `"__main__"``:` `    ``n ``=` `2` `    ``print``(summation(n))`

## Javascript

 ``

## C#

 `// C# program to calculate ` `// 1^2+2^2+3^2+...` `using` `System;` `class` `GFG ` `{`   `    ``// Function to calculate sum` `    ``public` `static` `int` `summation(``int` `n)` `    ``{` `        ``int` `sum = 0;` `        ``for` `(``int` `i = 1; i <= n; i++)` `            ``sum += (i * i);`   `        ``return` `sum;` `    ``}`   `    ``// Driver code` `    ``public` `static` `void` `Main()` `    ``{` `        ``int` `n = 2;`   `        ``Console.WriteLine(summation(n));` `    ``}` `}`   `// This code is contributed by vt_m`

## PHP

 ``

Output

`5`

Time Complexity: O(n)
Auxiliary Space: O(1), since no extra space has been taken.

Efficient Approach :
There exists a formula for finding the sum of squares of first n numbers.
1 + 2 + ……….. + n = n(n+1) / 2
12 + 22 + ……… + n2 = n(n+1)(2n+1) / 6

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

Example : n = 3
= 3 * (3 + 1) * (2*3 + 1) / 6
= (3 * 4 * 7) / 6
= 84 / 6
= 14```

How does this work?

```We can prove this formula using induction.
We can easily see that the formula is true for
n = 1 and n = 2 as sums are 1 and 5 respectively.

Let it be true for n = k-1. So sum of k-1 numbers
is (k - 1) * k * (2 * k - 1)) / 6

In the following steps, we show that it is true
for k assuming that it is true for k-1.

Sum of k numbers = Sum of k-1 numbers + k2
= (k - 1) * k * (2 * k - 1) / 6 + k2
= ((k2 - k) * (2*k - 1) + 6k2)/6
= (2k3 - 2k2 - k2 + k + 6k2)/6
= (2k3 + 3k2 + k)/6
= k * (k + 1) * (2*k + 1) / 6```

## C

 `// C program to get the sum ` `// of the following series` `#include `   `// Function calculating` `// the series` `int` `summation(``int` `n)` `{` `    ``return` `(n * (n + 1) * ` `           ``(2 * n + 1)) / 6;` `}`   `// Driver Code` `int` `main()` `{` `    ``int` `n = 10;` `    ``printf``(``"%d"``, summation(n));` `    ``return` `0;` `}`

## C++

 `// C++ program to get the sum ` `// of the following series` `#include ` `using` `namespace` `std;`   `// Function calculating` `// the series` `int` `summation(``int` `n)` `{` `    ``return` `(n * (n + 1) * ` `        ``(2 * n + 1)) / 6;` `}`   `// Driver Code` `int` `main()` `{` `    ``int` `n = 10;` `    ``cout << summation(n) << endl;` `    ``return` `0;` `}`   `// This code is contributed by shubhamsingh10`

## Java

 `// Java program to get ` `// the sum of the series` `import` `java.util.*;` `import` `java.lang.*;`   `class` `GFG ` `{` `    ``// Function calculating ` `    ``// the series` `    ``public` `static` `int` `summation(``int` `n)` `    ``{` `        ``return` `(n * (n + ``1``) * ` `               ``(``2` `* n + ``1``)) / ``6``;` `    ``}`   `    ``// Driver Code` `    ``public` `static` `void` `main(String args[])` `    ``{` `        ``int` `n = ``10``;` `        ``System.out.println(summation(n));` `    ``}` `}`   `// This code is contributed` `// by Sachin Bisht`

## Python3

 `# Python code to find sum of ` `# squares of first n natural numbers.` `def` `summation(n):` `    ``return` `(n ``*` `(n ``+` `1``) ``*` `           ``(``2` `*` `n ``+` `1``)) ``/` `6` `    `  `# Driver Code` `if` `__name__ ``=``=` `'__main__'``:` `    ``n ``=` `10` `    ``print``(summation(n))`

## Javascript

 `

`             ``

## C#

 `// C# program to get the sum` `// of the series` `using` `System;`   `class` `GFG ` `{`   `    ``// Function calculating` `    ``// the series` `    ``public` `static` `int` `summation(``int` `n)` `    ``{` `        ``return` `(n * (n + 1) * ` `               ``(2 * n + 1)) / 6;` `    ``}`   `    ``// Driver Code` `    ``public` `static` `void` `Main()` `    ``{` `        ``int` `n = 10;`   `        ``Console.WriteLine(summation(n));` `    ``}` `}`   `// This code is contributed by vt_m`

## PHP

 ``

Output

`385`

Time Complexity: O(1)
Auxiliary Space: O(1)

Avoiding the overflow:
In the above method, sometimes due to large value of n, the value of (n * (n + 1) * (2 * n + 1)) would overflow. We can avoid this overflow up to some extent using the fact that n*(n+1) must be divisible by 2.

Below is the code for the above approach.

## C++

 `// C++ program to get the sum` `// of the following series` `#include ` `using` `namespace` `std;`   `// Function calculating` `// the series` `int` `summation(``int` `n)` `{` `    ``return` `(n * (n + 1) / 2) * (2 * n + 1) / 3;` `}`   `// Driver Code` `int` `main()` `{` `    ``int` `n = 10;` `    ``cout << summation(n) << endl;` `    ``return` `0;` `}`   `// This code is contributed by Pushpesh Raj`

## Java

 `// Java program to get the sum` `// of the following series` `import` `java.io.*;`   `class` `GFG {`   `  ``// Function calculating` `  ``// the series` `  ``static` `int` `summation(``int` `n)` `  ``{` `    ``return` `(n * (n + ``1``) / ``2``) * (``2` `* n + ``1``) / ``3``;` `  ``}`   `  ``// Driver function` `  ``public` `static` `void` `main (String[] args) {` `    ``int` `n = ``10``;` `    ``System.out.println(summation(n));`   `  ``}` `}`   `// This code is contributed by Aman Kumar.`

## Python3

 `# Python program to get the sum` `# of the following series`   `# Function calculating` `# the series` `def` `summation(n):` `    ``return` `(n ``*` `(n ``+` `1``) ``/``/` `2``) ``*` `(``2` `*` `n ``+` `1``) ``/``/` `3`   `# Driver Code` `def` `main():` `    ``n ``=` `10` `    ``print``(summation(n))`   `if` `__name__ ``=``=` `"__main__"``:` `    ``main()`   `# This code is contributed by shubhamsingh`

## Javascript

 `// Javascript program to get the sum` `// of the following series`   `// Function calculating` `// the series` `function` `summation(n)` `{` `    ``return` `(n * (n + 1) / 2) * (2 * n + 1) / 3;` `}`   `// Driver Code` `n = 10;` `console.log(summation(n));`   `// This code is contributed by Pushpesh Raj`

## C#

 `using` `System;` `class` `MainClass ` `{`   `  ``// Function calculating the series` `  ``public` `static` `int` `Summation(``int` `n)` `  ``{` `    ``return` `(n * (n + 1) / 2) * (2 * n + 1) / 3;` `  ``}`   `  ``public` `static` `void` `Main(``string``[] args)` `  ``{` `    ``int` `n = 10;` `    ``Console.WriteLine(Summation(n));` `  ``}` `}`   `// This code is contributed by divyansh2212`

Output

`385`

Time complexity: O(1)

Auxiliary Space: O(1)

### Method 4: Using recursion

1. The function sum_of_squares(n) is defined with n as the parameter.
2. The base case is defined where if n equals 1, then the function returns 1.
3. For values of n greater than 1, the function returns the square of n plus the sum of squares of n-1.
4. The function is called with n=8 using print(sum_of_squares(n)).
5. Since n is greater than 1, the function returns 8^2 + sum_of_squares(7).
6. In the next recursion, n=7, so the function returns 7^2 + sum_of_squares(6).
7. This recursion continues until the base case is reached for n=1, where the function returns 1.
8. The final value of the sum of squares for n=8 is calculated as 1^2 + 2^2 + 3^2 + … + 7^2 + 8^2 = 204.

## C++

 `#include `   `int` `sum_of_squares(``int` `n) {` `    ``if` `(n == 1) {` `        ``return` `1;` `    ``} ``else` `{` `        ``return` `n * n + sum_of_squares(n - 1);` `    ``}` `}`   `int` `main() {` `    ``int` `n = 8;` `    ``std::cout << sum_of_squares(n) << std::endl;` `    ``return` `0;` `}`

## Java

 `public` `class` `Main {` `    ``public` `static` `int` `sum_of_squares(``int` `n) {` `        ``if` `(n == ``1``) {` `            ``return` `1``;` `        ``} ``else` `{` `            ``return` `n * n + sum_of_squares(n - ``1``);` `        ``}` `    ``}`   `    ``public` `static` `void` `main(String[] args) {` `        ``int` `n = ``8``;` `        ``System.out.println(sum_of_squares(n));` `    ``}` `}`   `// This code is contributed by shivhack999`

## Python3

 `def` `sum_of_squares(n):` `    ``if` `n ``=``=` `1``:` `        ``return` `1` `    ``else``:` `        ``return` `n``*``*``2` `+` `sum_of_squares(n``-``1``)` `n``=``8` `print``(sum_of_squares(n))`

## Javascript

 `function` `sumOfSquares(n) {` `  ``if` `(n == 1) {` `    ``return` `1;` `  ``} ``else` `{` `    ``return` `n * n + sumOfSquares(n - 1);` `  ``}` `}`   `let n = 8;` `console.log(sumOfSquares(n));`

## C#

 `using` `System;`   `class` `Program {` `    ``static` `int` `SumOfSquares(``int` `n)` `    ``{` `        ``if` `(n == 1) {` `            ``return` `1;` `        ``}` `        ``else` `{` `            ``return` `n * n + SumOfSquares(n - 1);` `        ``}` `    ``}` `    ``static` `void` `Main(``string``[] args)` `    ``{` `        ``int` `n = 8;` `        ``Console.WriteLine(SumOfSquares(n));` `    ``}` `}`

Output

`204`

Time complexity of this function is O(n), since the function needs to call itself recursively n times.

The space complexity is also O(n) due to the recursive calls on the stack.

Previous
Next