Number of Self-Divisible Permutations - Problem
Given an integer n, return the number of self-divisible permutations of the 1-indexed array nums = [1, 2, 3, ..., n].
A 1-indexed array a of length n is self-divisible if for every 1 <= i <= n, gcd(a[i], i) == 1 (where gcd is the greatest common divisor).
A permutation of an array is a rearrangement of its elements. For example, the permutations of [1, 2, 3] are: [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1].
Input & Output
Example 1 — Small Case
$
Input:
n = 2
›
Output:
1
💡 Note:
Array is [1,2]. For [1,2]: gcd(1,1)=1 ✓, gcd(2,2)=2 ✗. For [2,1]: gcd(2,1)=1 ✓, gcd(1,2)=1 ✓. Only 1 valid arrangement.
Example 2 — Larger Case
$
Input:
n = 3
›
Output:
2
💡 Note:
Need gcd(a[i], i) = 1 for all i. Valid arrangements: [2,1,3] and [3,1,2]. All other permutations fail the GCD constraint.
Example 3 — Edge Case
$
Input:
n = 1
›
Output:
1
💡 Note:
Array is [1]. Only arrangement [1]: gcd(1,1)=1 ✓. One valid permutation.
Constraints
- 1 ≤ n ≤ 15
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array [1,2,3,...,n] to permute
2
Constraint
gcd(a[i], i) = 1 for all positions
3
Output
Count of valid arrangements
Key Takeaway
🎯 Key Insight: Pre-compute valid number placements based on GCD constraint to prune search space efficiently
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code