Program for cube sum of first n natural numbers | Efficient CPP program to find sum of cubes of first n natural numbers that avoids overflow if result is going to be withing limits . ; Returns sum of first n natural numbers ; Driver code
#include <iostream> NEW_LINE using namespace std ; int sumOfSeries ( int n ) { int x ; if ( n % 2 == 0 ) x = ( n / 2 ) * ( n + 1 ) ; else x = ( ( n + 1 ) / 2 ) * n ; return x * x ; } int main ( ) { int n = 5 ; cout << sumOfSeries ( n ) ; return 0 ; }