Sum of series formed by difference between product and sum of N natural numbers | Function to calculate the sum upto Nth term ; Stores the sum of the series ; Stores the product of natural numbers upto the current term ; Stores the sum of natural numbers upto the upto current term ; Generate the remaining terms and calculate sum ; Update the sum ; Return the sum ; Driver code
function seriesSum ( n ) { let sum = 0 ; let currProd = 1 ; let currSum = 1 ; for ( let i = 2 ; i <= n ; i ++ ) { currProd *= i ; currSum += i ; sum += currProd - currSum ; } return sum ; } let N = 5 ; document . write ( seriesSum ( N ) + " " ) ;