๐ฏ Find the Self-Divisible Permutations
Given an integer n, you need to find how many ways you can arrange the numbers [1, 2, 3, ..., n] such that each number and its position are relatively prime (their greatest common divisor equals 1).
What makes a permutation "self-divisible"?
A 1-indexed array a of length n is self-divisible if for every position i (from 1 to n), gcd(a[i], i) == 1.
Example: For n=3, consider the permutation [2, 1, 3]:
โข Position 1: gcd(2, 1) = 1 โ
โข Position 2: gcd(1, 2) = 1 โ
โข Position 3: gcd(3, 3) = 3 โ 1 โ
This is a classic constraint satisfaction problem that combines permutation generation with number theory. You'll need to efficiently explore all valid arrangements while pruning invalid paths early.
Input & Output
Visualization
Time & Space Complexity
We potentially generate all n! permutations, each taking O(n) time to validate
Recursion depth is O(n) for the current permutation being built
Constraints
- 1 โค n โค 15
- The answer is guaranteed to fit in a 32-bit integer
- Note: Array is 1-indexed, so position numbering starts from 1