Program to find sum of first n natural numbers | Efficient JAVA program to find sum of first n natural numbers that avoids overflow if result is going to be within limits . ; Returns sum of first n natural numbers ; If n is odd , ( n + 1 ) must be even ; Driver code
import java . io . * ; class GFG { static int findSum ( int n ) { if ( n % 2 == 0 ) return ( n / 2 ) * ( n + 1 ) ; else return ( ( n + 1 ) / 2 ) * n ; } public static void main ( String args [ ] ) { int n = 5 ; System . out . println ( findSum ( n ) ) ; } }