Prime Arrangements - Problem

Return the number of permutations of 1 to n so that prime numbers are at prime indices (1-indexed).

Recall that an integer is prime if and only if it is greater than 1, and cannot be written as a product of two positive integers both smaller than it.

Since the answer may be large, return the answer modulo 10^9 + 7.

Input & Output

Example 1 — Small Case
$ Input: n = 5
Output: 12
💡 Note: For n=5, we have primes [2,3,5] and non-primes [1,4]. Prime positions are [2,3,5] and non-prime positions are [1,4]. We can arrange 3 primes in 3 prime positions in 3! = 6 ways, and 2 non-primes in 2 non-prime positions in 2! = 2 ways. Total = 6 × 2 = 12.
Example 2 — Minimum Case
$ Input: n = 1
Output: 1
💡 Note: For n=1, there's only number 1 (non-prime) at position 1 (non-prime). Only one valid arrangement: [1]. Result = 1! = 1.
Example 3 — Even Case
$ Input: n = 4
Output: 4
💡 Note: For n=4, primes are [2,3] and non-primes are [1,4]. Prime positions are [2,3] and non-prime positions are [1,4]. Arrangements = 2! × 2! = 2 × 2 = 4.

Constraints

  • 1 ≤ n ≤ 100

Visualization

Tap to expand
Prime Arrangements INPUT Indices 1 to n = 5 1 2 3 4 5 Yellow = Prime indices (2,3,5) Numbers 1 to 5: 1 2 3 4 5 Green = Prime numbers (2,3,5) Input Value n = 5 ALGORITHM STEPS 1 Count Primes Primes up to 5: 2,3,5 Count = 3 2 Count Non-Primes Non-primes: 1,4 Count = 2 3 Calculate Factorials 3! = 3x2x1 = 6 2! = 2x1 = 2 4 Multiply Results 3! x 2! = 6 x 2 = 12 Formula: primeCount! x nonPrimeCount! mod (10^9 + 7) FINAL RESULT Valid Arrangement Example: 1 2 3 4 5 Primes at prime indices: OK Permutation Breakdown Prime positions (2,3,5): 3! = 6 Non-prime positions (1,4): 2! = 2 Total: 6 x 2 = 12 OUTPUT 12 Key Insight: Primes must go to prime indices, non-primes to non-prime indices. The answer is simply: (count of primes)! x (count of non-primes)! mod (10^9 + 7) Use Sieve of Eratosthenes to count primes efficiently in O(n log log n) time. TutorialsPoint - Prime Arrangements | Optimal Solution
Asked in
Google 15 Amazon 12 Microsoft 8
28.0K Views
Medium Frequency
~15 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen