Friends Pairing Problem | Python3 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
fact = [ 1 ] NEW_LINE def preComputeFact ( n ) : NEW_LINE INDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT fact . append ( ( fact [ i - 1 ] * i ) ) NEW_LINE DEDENT DEDENT def countFriendsPairings ( n ) : NEW_LINE INDENT ones = n NEW_LINE twos = 1 NEW_LINE ans = 0 NEW_LINE while ( ones >= 0 ) : NEW_LINE INDENT ans = ans + ( fact [ n ] // ( twos * fact [ ones ] * fact [ ( n - ones ) // 2 ] ) ) NEW_LINE ones = ones - 2 NEW_LINE twos = twos * 2 NEW_LINE DEDENT return ( ans ) NEW_LINE DEDENT preComputeFact ( 1000 ) NEW_LINE n = 4 NEW_LINE print ( countFriendsPairings ( n ) ) NEW_LINE