Open In App

Java Program for Sum of squares of first n natural numbers

Last Updated : 12 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a positive integer N. The task is to find 12 + 22 + 32 + ….. + N2.
Examples: 

Input : N = 4
Output : 30
12 + 22 + 32 + 42
= 1 + 4 + 9 + 16
= 30

Input : N = 5
Output : 55

Method 1: O(N) The idea is to run a loop from 1 to n and for each i, 1 <= i <= n, find i2 to sum. 

Java




// Java Program to find sum of
// square of first n natural numbers
import java.io.*;
 
class GFG {
 
    // Return the sum of square of first n natural numbers
    static int squaresum(int n)
    {
        // Iterate i from 1 and n
        // finding square of i and add to sum.
        int sum = 0;
        for (int i = 1; i <= n; i++)
            sum += (i * i);
        return sum;
    }
 
    // Driven Program
    public static void main(String args[]) throws IOException
    {
        int n = 4;
        System.out.println(squaresum(n));
    }
}
 
/*This code is contributed by Nikita Tiwari.*/


Output: 

30

 

Time Complexity : O(n)

Auxiliary Space: O(1)

Method 2:

Proof: 

We know,
(k + 1)3 = k3 + 3 * k2 + 3 * k + 1
We can write the above identity for k from 1 to n:
23 = 13 + 3 * 12 + 3 * 1 + 1 ......... (1)
33 = 23 + 3 * 22 + 3 * 2 + 1 ......... (2)
43 = 33 + 3 * 32 + 3 * 3 + 1 ......... (3)
53 = 43 + 3 * 42 + 3 * 4 + 1 ......... (4)
...
n3 = (n - 1)3 + 3 * (n - 1)2 + 3 * (n - 1) + 1 ......... (n - 1)
(n + 1)3 = n3 + 3 * n2 + 3 * n + 1 ......... (n)

Putting equation (n - 1) in equation n,
(n + 1)3 = (n - 1)3 + 3 * (n - 1)2 + 3 * (n - 1) + 1 + 3 * n2 + 3 * n + 1
         = (n - 1)3 + 3 * (n2 + (n - 1)2) + 3 * ( n + (n - 1) ) + 1 + 1

By putting all equation, we get
(n + 1)3 = 13 + 3 * ? k2 + 3 * ? k + ? 1
n3 + 3 * n2 + 3 * n + 1 = 1 + 3 * ? k2 + 3 * (n * (n + 1))/2 + n
n3 + 3 * n2 + 3 * n = 3 * ? k2 + 3 * (n * (n + 1))/2 + n
n3 + 3 * n2 + 2 * n - 3 * (n * (n + 1))/2 = 3 * ? k2
n * (n2 + 3 * n + 2) - 3 * (n * (n + 1))/2 = 3 * ? k2
n * (n + 1) * (n + 2) - 3 * (n * (n + 1))/2 = 3 * ? k2
n * (n + 1) * (n + 2 - 3/2) = 3 * ? k2
n * (n + 1) * (2 * n + 1)/2  = 3 * ? k2
n * (n + 1) * (2 * n + 1)/6  = ? k2

Java




// Java Program to find sum
// of square of first n
// natural numbers
import java.io.*;
 
class GFG {
 
    // Return the sum of square
    // of first n natural numbers
    static int squaresum(int n)
    {
        return (n * (n + 1) * (2 * n + 1)) / 6;
    }
 
    // Driven Program
    public static void main(String args[])
        throws IOException
    {
        int n = 4;
        System.out.println(squaresum(n));
    }
}
 
/*This code is contributed by Nikita Tiwari.*/


Output: 

30

 

Avoiding early overflow: 
For large n, the value of (n * (n + 1) * (2 * n + 1)) would overflow. We can avoid overflow up to some extent using the fact that n*(n+1) must be divisible by 2.

Java




// Java Program to find sum of square of first
// n natural numbers. This program avoids
// overflow upto some extent for large value
// of n.
 
import java.io.*;
import java.util.*;
 
class GFG {
    // Return the sum of square of first n natural
    // numbers
    public static int squaresum(int n)
    {
        return (n * (n + 1) / 2) * (2 * n + 1) / 3;
    }
 
    public static void main(String[] args)
    {
        int n = 4;
        System.out.println(squaresum(n));
    }
}
 
// Code Contributed by Mohit Gupta_OMG <(0_o)>


Output: 

30

 

Time complexity: O(1) as it is doing constant operations

Auxiliary Space: O(1) as it is using constant space

Please refer complete article on Sum of squares of first n natural numbers for more details!



Similar Reads

Java Program for cube sum of first n natural numbers
Write a Java program to print the sum of series 13 + 23 + 33 + 43 + .......+ n3 till the n-th term. Examples: Input: n = 5Output: 225Explanation: 13 + 23 + 33 + 43 + 53 = 225 Input: n = 7Output: 784Explanation: 13 + 23 + 33 + 43 + 53 + 63 + 73 = 784 Java Program for cube sum of first n natural numbers using Naive Approach:Define the function sumOfC
4 min read
Java Program to Calculate Sum of First N Natural Numbers
In this article, we will check How to calculate the sum of N natural numbers using an iterative approach i.e. using a for a loop and Mathematical Formulae. Example to Find Sum of N Natural Numbers:Input: N = 10Output: Sum of first 10 Natural Number = 55 Input: N = 5Output: Sum of first 5 Natural Number = 15 Methods to Find the Sum of N Natural Numb
3 min read
Sum of first N natural numbers when N is extremely large
Given a positive integer n, the task is to find the sum of the first n natural numbers given that n is very large (1 ? n ? 1020000). Examples: Input: n = 4Output: 10 1 + 2 + 3 + 4 = 10 Input: n = 12345678910Output: 76207893880582233505 Approach: Sum of first n natural numbers is (n * (n + 1)) / 2 but given that n can be extremely large (1 ? n ? 102
6 min read
Java Program to Find Sum of Natural Numbers Using While Loop
While loop arises into play where beforehand there is no conclusive evidence that how many times a loop is to be executed. This is the primary reason as there is no strict tight bound over how many numbers the sum is to be evaluated. Situations in which the output can be displayed using test condition abiding hardcoded outputs by simply running the
3 min read
Java Program to Find Sum of Fibonacci Series Numbers of First N Even Indexes
For a given positive integer N, the purpose is to find the value of F2 + F4 + F6 +………+ F2n till N number. Where Fi indicates the i'th Fibonacci number. The Fibonacci Series is the numbers in the below-given integer sequence. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ……Examples: Input: n = 4 Output: 33 N = 4, So here the fibonacci series will be prod
4 min read
Java Program to Find the Sum of First N Odd &amp; Even Numbers
When any number which ends with 0,2,4,6,8 is divided by 2 that is an even number. And when any number ends with 1,3,5,7,9 is not divided by two is an odd number. Example: Input : 8 Output: Sum of First 8 Even numbers = 72 Sum of First 8 Odd numbers = 64Approach #1: Iterative Create two variables evenSum and oddSum and initialize them by 0.Start For
3 min read
How to Implement a FIFO (First-In-First-Out) Queue in Java?
FIFO stands for First In, First Out, which is a common way of organizing and manipulating Data Structure. In FIFO, the first element that is added to the data structure is the same first element that is to be removed first. Queue is a FIFO-based Data Structure. Here, the insert operation is called Enque, and it is added always at the start, and the
3 min read
Java Program to Rotate all odd numbers right and all even numbers left in an Array of 1 to N
Given a permutation arrays A[] consisting of N numbers in range [1, N], the task is to left rotate all the even numbers and right rotate all the odd numbers of the permutation and print the updated permutation. Note: N is always even.Examples:  Input: A = {1, 2, 3, 4, 5, 6, 7, 8} Output: {7, 4, 1, 6, 3, 8, 5, 2} Explanation: Even element = {2, 4, 6
2 min read
Java Program to Compute the Sum of Numbers in a List Using Recursion
ArrayList is a part of the Collection framework and is present in java.util package. It provides us with dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. This class is found in java.util package. Illustration: Input : [1, 3, 9] Output : 13 Here th
5 min read
Java Program to Find Sum of N Numbers Using Recursion
Recursion is a process by which a function calls itself repeatedly till it falls under the base condition and our motive is achieved. To solve any problem using recursion, we should simply follow the below steps: Assume/Identify the smaller problem from the problem which is similar to the bigger/original problem.Decide the answer to the smallest va
4 min read
Article Tags :