Count Derangements ( Permutation such that no element appears in its original position ) | Function to count derangements ; Base case ; Variable for just storing previous values ; Using above recursive formula ; Return result for n ; Driver code
function countDer ( n ) { if ( n == 1 n == 2 ) { return n - 1 ; } let a = 0 ; let b = 1 ; for ( let i = 3 ; i <= n ; ++ i ) { let cur = ( i - 1 ) * ( a + b ) ; a = b ; b = cur ; } return b ; } document . write ( " " + countDer ( 4 ) ) ;