Sum of kth powers of first n natural numbers | A global array to store factorial ; Function to calculate the factorials of all the numbers upto k ; Function to return the binomial coefficient ; nCr = ( n ! * ( n - r ) ! ) / r ! ; Function to return the sum of kth powers of n natural numbers ; When j is unity ; Calculating sum ( n ^ 1 ) of unity powers of n ; storing sum ( n ^ 1 ) for sum ( n ^ 2 ) ; If k = 1 then temp is the result ; For finding sum ( n ^ k ) removing 1 and n * kCk from ( n + 1 ) ^ k ; Removing all kC2 * sum ( n ^ ( k - 2 ) ) + ... + kCk - 1 * ( sum ( n ^ ( k - ( k - 1 ) ) ; Storing the result for next sum of next powers of k ; Driver code
< ? php $ MAX_K = 15 ; $ fac [ $ MAX_K ] = array ( ) ; function factorial ( $ k ) { global $ fac ; $ fac [ 0 ] = 1 ; for ( $ i = 1 ; $ i <= $ k + 1 ; $ i ++ ) { $ fac [ $ i ] = ( $ i * $ fac [ $ i - 1 ] ) ; } } function bin ( $ a , $ b ) { global $ MAX_K ; global $ fac ; $ ans = ( ( $ fac [ $ a ] ) / ( $ fac [ $ a - $ b ] * $ fac [ $ b ] ) ) ; return $ ans ; } function sumofn ( $ n , $ k ) { $ p = 0 ; $ num1 ; $ temp ; $ arr [ 1000 ] = array ( ) ; for ( $ j = 1 ; $ j <= $ k ; $ j ++ ) { if ( $ j == 1 ) { $ num1 = ( $ n * ( $ n + 1 ) ) / 2 ; $ arr [ $ p ++ ] = $ num1 ; $ temp = $ num1 ; } else { $ temp = ( pow ( $ n + 1 , $ j + 1 ) - 1 - $ n ) ; for ( $ s = 1 ; $ s < $ j ; $ s ++ ) { $ temp = $ temp - ( $ arr [ $ j - $ s - 1 ] * bin ( $ j + 1 , $ s + 1 ) ) ; } $ temp = $ temp / ( $ j + 1 ) ; $ arr [ $ p ++ ] = $ temp ; } } $ temp = $ arr [ $ p - 1 ] ; return $ temp ; } $ n = 5 ; $ k = 2 ; factorial ( $ k ) ; echo sumofn ( $ n , $ k ) , " STRNEWLINE " ; ? >