Sum of squares of first n natural numbers

28 May, 2022
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
Java
Python3
C#
PHP
Javascript
// CPP program to calculate// 1^2+2^2+3^2+...#include <iostream>using namespace std; // Function to calculate sumint summation(int n){    int sum = 0;    for (int i = 1; i <= n; i++)        sum += (i * i);     return sum;} // Driver codeint main(){    int n = 2;    cout << summation(n);    return 0;}
// C program to calculate// 1^2+2^2+3^2+...#include <stdio.h>  // Function to calculate sumint summation(int n){    int sum = 0;    for (int i = 1; i <= n; i++)        sum += (i * i);    return sum;}  // Driver codeint main(){    int n = 2;    printf("%d",summation(n));    return 0;}
// 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 program to# calculate 1 ^ 2 + 2 ^ 2 + 3 ^ 2+.. # Function to calculate seriesdef summation(n):    return sum([i**2 for i in               range(1, n + 1)]) # Driver Codeif __name__ == "__main__":    n = 2    print(summation(n))
// 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// PHP program to calculate// 1^2+2^2+3^2+... // Function to calculate sumfunction summation($n){    $sum = 0;    for ($i = 1; $i <= $n; $i++)        $sum += ($i * $i);     return $sum;}     // Driver code    $n = 2;    echo summation($n);     // This code is contributed by aj_36?>
<script>// JavaScript program to calculate// 1^2+2^2+3^2+...     // Function to calculate sum    function summation(n)    {        let sum = 0;        for (let i = 1; i <= n; i++)            sum += (i * i);           return sum;    }       // Driver code     let n = 2;    document.write(summation(n)); // This code is contributed by Surbhi Tyagi </script>
Output :  
5
Time Complexity: O(n)Auxiliary Space: O(1)
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
Java
Python3
C#
PHP
Javascript
// C++ program to get the sum// of the following series#include <iostream>using namespace std; // Function calculating// the seriesint summation(int n){    return (n * (n + 1) *        (2 * n + 1)) / 6;} // Driver Codeint main(){    int n = 10;    cout << summation(n) << endl;    return 0;} // This code is contributed by shubhamsingh10
// C program to get the sum// of the following series#include <stdio.h> // Function calculating// the seriesint summation(int n){    return (n * (n + 1) *           (2 * n + 1)) / 6;} // Driver Codeint main(){    int n = 10;    printf("%d", summation(n));    return 0;}
// Java program to get// the sum of the seriesimport 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
# Python code to find sum of# squares of first n natural numbers.def summation(n):    return (n * (n + 1) *           (2 * n + 1)) / 6     # Driver Codeif __name__ == '__main__':    n = 10    print(summation(n))
// C# program to get the sum// of the seriesusing 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// PHP program to get the// sum of the following series // Function calculating// the seriesfunction summation($n){    return ($n * ($n + 1) *           (2 * $n + 1)) / 6;} // Driver Code$n = 10;echo summation($n); // This code is contributed by aj_36?>
<p id="demo"></p>    <script>var x = summation(10);document.getElementById("demo").innerHTML = x; function summation(n) {  return (n * (n + 1) *        (2 * n + 1)) / 6;}</script>
Output :  
385
Time Complexity: O(1)Auxiliary Space: O(1) 
jit_t
SHUBHAMSINGH10
Akanksha_Rai
surbhityagi15
sravankumar8128
kothavvsaakash
number-theory
series
Mathematical
number-theory
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Prime Numbers
Find minimum number of coins that make a given value
Minimum number of jumps to reach end
The Knight's tour problem | Backtracking-1
Algorithm to solve Rubik's Cube
Program for Decimal to Binary Conversion
Modulo 10^9+7 (1000000007)
Modulo Operator (%) in C/C++ with Examples