# Program to find number of elements in all permutation which are following given conditions in Python

Suppose we have a set A where all elements from 1 to n are present. And P(A) represents all permutations of elements present in A. We have to find number of elements in P(A) which satisfies the given conditions

• For all i in range [1, n], A[i] is not same as i
• There exists a set of k indices {i1, i2, ... ik} such that A[ij] = ij+1 for all j < k and A[ik] = i1 (cyclic).

So, if the input is like n = 3 k = 2, then the output will be 0 because -

Consider the Array's are 1 indexed. As N = 3 and K = 2, we can find 2 sets of A that satisfy the first property a[i] ≠ i, they are [3,1,2] and [2,3,1]. Now as K = 2, we can have 6 such elements.

[1,2], [1,3],[2,3], [2,1], [3,1], [3,2]. Now if we consider the first element of

P(A) -> [3,1,2]

• [1,2], A[1] ≠ 2
• [1,3], A[1] = 3 but A[3] ≠ 1
• [2,3], A[2] ≠ 3
• [2,1], A[2] = 1 but A[1] ≠ 2
• [3,1], A[3] = 1 but A[1] ≠ 3
• [3,2], A[3] ≠ 2

P(A) -> [2,3,1]

• [1,2], A[1] = 2 but A[2] ≠ 1
• [1,3], A[1] ≠ 3
• [2,3], A[2] = 3 but A[3] ≠ 3
• [2,1], A[2] ≠ 1
• [3,1], A[3] = but A[1] ≠ 3
• [3,2], A[3] ≠ 2

As none of the elements of a satisfy the properties above, hence 0.

To solve this, we will follow these steps −

• ps := all permutations of arrays with elements in range [1, n]
• c := 0
• for each p in ps, do
• for each index i and value a in p, do
• if a is same as i, then
• come out from the loop
• otherwise,
• for j in range 0 to n - 1, do
• current := p[j]
• cycle_length := 1
• while current is not same as j, do
• current := p[current]
• cycle_length := cycle_length + 1
• if cycle_length is same as k, then
• c := c + 1
• come out from the loop
• return c

## Example

Let us see the following implementation to get better understanding −

import itertools

def solve(n, k):
ps = itertools.permutations(range(n), n)
c = 0
for p in ps:
for i, a in enumerate(p):
if a == i:
break
else:
for j in range(n):
current = p[j]
cycle_length = 1
while current != j:
current = p[current]
cycle_length += 1
if cycle_length == k:
c += 1
break
return c

n = 3
k = 2
print(solve(n, k))

## Input

3, 2


## Output

0