Java Program - Calculate sum of Squares of Natural numbers
In Mathematics, the natural numbers are all positive numbers which is used for counting like 1, 2, 3, 4, and so on. The smallest natural number is 1.
Objective: Write a Java program which returns sum of squares of natural numbers starting from 1 to given natural number n, (12 + 22 + 32 + ... + n2).
Method 1: Using while loop
The example below shows how to use while loop to calculate sum of squares of first n natural numbers.
public class MyClass { public static void main(String[] args) { int n = 10; int i = 1; int sum = 0; //calculating sum of squares from 1 to n while(i <= n) { sum += i*i; i++; } System.out.println("Sum is: " + sum); } }
The above code will give the following output:
Sum is: 385
Method 2: Using for loop
The same can be achieved using for loop. Consider the example below:
public class MyClass { public static void main(String[] args) { int n = 10; int sum = 0; //calculating sum of squares from 1 to n for(int i = 1; i <= n; i++) sum += i*i; System.out.println("Sum is: " + sum); } }
The above code will give the following output:
Sum is: 385
Method 3: Using Recursion
Similarly, recursion can be used to calculate the sum.
public class MyClass { //recursive method static int Sum(int n) { if(n == 1) return 1; else return (n*n + Sum(n-1)); } public static void main(String[] args) { System.out.println("Sum of Squares of first 10 natural numbers: " + Sum(10)); System.out.println("Sum of Squares of first 20 natural numbers: " + Sum(20)); } }
The above code will give the following output:
Sum of Squares of first 10 natural numbers: 385 Sum of Squares of first 20 natural numbers: 2870
Method 4: Using Mathematical Formula
The sum of squares of first n natural numbers can be mathematically expressed as:
public class MyClass { public static void main(String[] args) { int n = 10; //calculating sum of squares from 1 to n int sum = n*(n+1)*(2*n+1)/6; System.out.println("Sum is: " + sum); } }
The above code will give the following output:
Sum is: 385
Recommended Pages
- Java Program - To Check Prime Number
- Java Program - Bubble Sort
- Java Program - Selection Sort
- Java Program - Maximum Subarray Sum
- Java Program - Reverse digits of a given Integer
- Java - Swap two numbers
- Java Program - Fibonacci Sequence
- Java Program - Insertion Sort
- Java Program - Find Factorial of a Number
- Java Program - Find HCF of Two Numbers
- Java Program - Merge Sort
- Java Program - Shell Sort
- Stack in Java
- Queue in Java
- Java Program - Find LCM of Two Numbers
- Java Program - To Check Whether a Number is Palindrome or Not
- Java Program - To Check Whether a String is Palindrome or Not
- Java Program - Heap Sort
- Java Program - Quick Sort
- Java - Swap Two Numbers without using Temporary Variable