Program for cube sum of first n natural numbers | Efficient Java program to find sum of cubes of first n natural numbers that avoids overflow if result is going to be withing limits . ; Returns the sum of series ; Driver Function
import java . util . * ; import java . lang . * ; class GFG { public static int sumOfSeries ( int n ) { int x ; if ( n % 2 == 0 ) x = ( n / 2 ) * ( n + 1 ) ; else x = ( ( n + 1 ) / 2 ) * n ; return x * x ; } public static void main ( String [ ] args ) { int n = 5 ; System . out . println ( sumOfSeries ( n ) ) ; } }