Number of ways in which an item returns back to its initial position in N swaps in array of size K | Python3 program to find the number of ways in which an item returns back to its initial position in N swaps in an array of size K ; Function to calculate ( x ^ y ) % p in O ( log y ) ; Initialize result ; Update x if it is more than or equal to p ; If y is odd , multiply x with result ; y must be even now y = y / 2 ; Function to return the number of ways ; Base case ; Recursive case F ( n ) = ( k - 1 ) ^ ( n - 1 ) - F ( n - 1 ) . ;  ; Function calling
mod = 1000000007 NEW_LINE def power ( x , y ) : NEW_LINE INDENT p = mod NEW_LINE res = 1 NEW_LINE x = x % p NEW_LINE while ( y > 0 ) : NEW_LINE INDENT if ( y & 1 ) != 0 : NEW_LINE INDENT res = ( res * x ) % p NEW_LINE DEDENT y = y >> 1 NEW_LINE x = ( x * x ) % p NEW_LINE DEDENT return res NEW_LINE DEDENT def solve ( n , k ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return ( power ( ( k - 1 ) , n - 1 ) % mod - solve ( n - 1 , k ) + mod ) % mod NEW_LINE DEDENT / * Driver code * / NEW_LINE n , k = 4 , 5 NEW_LINE print ( solve ( n , k ) ) NEW_LINE