K | Function that finds the Nth element of K - Fibonacci series ; If N is less than K then the element is '1' ; first k elements are 1 ; ( K + 1 ) th element is K ; find the elements of the K - Fibonacci series ; subtract the element at index i - k - 1 and add the element at index i - i from the sum ( sum contains the sum of previous ' K ' elements ) ; set the new sum ; Driver code ; get the Nth value of K - Fibonacci series
function solve ( N , K ) { var Arr = new Array ( N + 1 ) ; if ( N <= K ) { document . write ( " " + " " ) ; return ; } var i = 0 , sum = K ; for ( i = 1 ; i <= K ; ++ i ) { Arr [ i ] = 1 ; } Arr [ i ] = sum ; for ( var i = K + 2 ; i <= N ; ++ i ) { Arr [ i ] = sum - Arr [ i - K - 1 ] + Arr [ i - 1 ] ; sum = Arr [ i ] ; } document . write ( Arr [ N ] + " " ) ; } var N = 4 , K = 2 ; solve ( N , K ) ;