Count ways to reach the nth stair using step 1 , 2 or 3 | A recursive function used by countWays ; Declaring three variables and holding the ways for first three stairs ; Fourth variable ; Starting from 4 as already counted for 3 stairs ; Driver code
function countWays ( n ) { var a = 1 , b = 2 , c = 4 ; var d = 0 ; if ( n == 0 n == 1 n == 2 ) return n ; if ( n == 3 ) return c ; for ( var i = 4 ; i <= n ; i ++ ) { d = c + b + a ; a = b ; b = c ; c = d ; } return d ; } var n = 4 ; document . write ( countWays ( n ) ) ;