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.
//Java Program to Find the Sum of n Square Numbers
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class SumOfNSquareNumbers {
// Function to read n and display the sum
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n;
System.out.println("Enter the value of n");
try{
n = Integer.parseInt(br.readLine());
}catch (Exception e){
System.out.println("An error occurred");
return;
}
if(n<0){
System.out.println("n cannot take negative values");
return;
}
double sum = n*(n+1)*(2*n+1)/6;
System.out.println("The sum of first " + n + " squared numbers is " + sum);
}
}
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
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..
Related Posts:
- Check Programming Books
- Apply for Computer Science Internship
- Practice Information Technology MCQs
- Practice Programming MCQs
- Practice BCA MCQs