Friends Pairing Problem | Javascript soln using mathematical approach factorial array is stored dynamically ; Returns count of ways n people can remain single or paired up . ; pow of 1 will always be one ; Driver Code pre - compute factorial
let fact = [ 1 ] ; function preComputeFact ( n ) { for ( let i = 1 ; i < n + 1 ; i ++ ) { fact . push ( ( fact [ i - 1 ] * i ) ) ; } } function countFriendsPairings ( n ) { let ones = n let twos = 1 ; let ans = 0 ; while ( ones >= 0 ) { ans = ans + Math . floor ( fact [ n ] / ( twos * fact [ ones ] * fact [ ( n - ones ) / 2 ] ) ) ones = ones - 2 twos = twos * 2 } return ans ; } preComputeFact ( 1000 ) n = 4 document . write ( countFriendsPairings ( n ) )