Java Program to Find the Sum of n Square Numbers

This is the Java Program to Find the Sum of n Square Numbers.

Problem Description

Given an integer says n, find out the sum of the first n squared numbers.

Problem Solution

The sum of the first n squared numbers can be calculated using the formula :

sum = n*(n+1)*(2n+1)/6

Program/Source Code

Here is the source code of the Java Program to Find the Sum of n Square Numbers. The program is successfully compiled and tested using IDE IntelliJ Idea in Windows 7. The program output is also shown below.

  1.  
  2. //Java Program to Find the Sum of n Square Numbers
  3.  
  4. import java.io.BufferedReader;
  5. import java.io.InputStreamReader;
  6.  
  7. public class SumOfNSquareNumbers {
  8.     // Function to read n and display the sum
  9.     public static void main(String[] args) {
  10.         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  11.         int n;
  12.         System.out.println("Enter the value of n");
  13.         try{
  14.             n = Integer.parseInt(br.readLine());
  15.         }catch (Exception e){
  16.             System.out.println("An error occurred");
  17.             return;
  18.         }
  19.         if(n<0){
  20.             System.out.println("n cannot take negative values");
  21.             return;
  22.         }
  23.         double sum = n*(n+1)*(2*n+1)/6;
  24.         System.out.println("The sum of first " + n + " squared numbers is " + sum);
  25.     }
  26. }
Program Explanation

In the function main(), firstly an integer n is entered and then the sum is calculated as per the line,
double sum = n*(n+1)*(2*n+1)/6. Finally, the sum is displayed.

advertisement
advertisement

Time Complexity: O(1).

Runtime Test Cases
 
Case 1 (Simple Test Case):
 
Enter the value of n
15
The sum of first 15 squared numbers is 1240.0

Sanfoundry Global Education & Learning Series – Java Programs..

Note: Join free Sanfoundry classes at Telegram or Youtube

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.