Tuesday, November 3, 2015

Sum of the Squares of the First n Numbers Recursively in Java

Formula for the sum of the squares of the first n numbers is described with the following equation in mathematics.

 f(n) = [n(n+1)(2n+1)]/6

In order to get the result for the sum of the first n integers in Java a recursive method can be used.


package basics;

public class NumberUtils {

 public static int sumOfFirstNSquares( int number )
 {
  if( number == 0 )
   return 0;
  
  return sumOfFirstNSquares(number-1)+(number*number);
 }
 
 public static void main(String[] args) {
  
  int sum = sumOfFirstNSquares(5);
  System.out.println("Sum is = "+sum);
  
  sum = sumOfFirstNSquares(7);
  System.out.println("Sum is = "+sum);
  
  sum = sumOfFirstNSquares(11);
  System.out.println("Sum is = "+sum);
 }
}



Create a NumberUtils.java file in your workspace.

If you are willing to work with real big numbers in Java then a BigInteger can be a solution.

When the main method inside the NumberUtils class executed it is going to print :

Sum is = 55
Sum is = 140
Sum is = 506

No comments:

Post a Comment