Number of ways in which an item returns back to its initial position in N swaps in array of size K | C ++ 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 ) . ; Drivers code ; Function calling
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define mod  1000000007 NEW_LINE long long power ( long x , long y ) { long p = mod ; long res = 1 ; x = x % p ; while ( y > 0 ) { if ( y & 1 ) res = ( res * x ) % p ; y = y >> 1 ; x = ( x * x ) % p ; } return res ; } long long solve ( int n , int k ) { if ( n == 1 ) return 0LL ; return ( power ( ( k - 1 ) , n - 1 ) % mod - solve ( n - 1 , k ) + mod ) % mod ; } int main ( ) { int n = 4 , k = 5 ; cout << solve ( n , k ) ; return 0 ; }