fast_way is recursive method to calculate power
function fastPow ( N , K ) { if ( K == 0 ) return 1 ; let temp = fastPow ( N , Math . floor ( K / 2 ) ) ; if ( K % 2 == 0 ) return temp * temp ; else return N * temp * temp ; } function countWays ( N , K ) { return K * fastPow ( K - 1 , N - 1 ) ; }