LeetCode 题解工作台
质数排列
请你帮忙给从 1 到 n 的数设计排列方案,使得所有的「质数」都应该被放在「质数索引」(索引从 1 开始)上;你需要返回可能的方案总数。 让我们一起来回顾一下「质数」:质数一定是大于 1 的,并且不能用两个小于它的正整数的乘积来表示。 由于答案可能会很大,所以请你返回答案 模 mod 10^9 + …
1
题型
4
代码语言
3
相关题
当前训练重点
简单 · 数学·driven
答案摘要
先统计 范围内的质数个数,我们记为 。然后求 以及 阶乘的乘积得到答案,注意取模操作。 这里我们用“埃氏筛”统计质数。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·driven 题型思路
题目描述
请你帮忙给从 1 到 n 的数设计排列方案,使得所有的「质数」都应该被放在「质数索引」(索引从 1 开始)上;你需要返回可能的方案总数。
让我们一起来回顾一下「质数」:质数一定是大于 1 的,并且不能用两个小于它的正整数的乘积来表示。
由于答案可能会很大,所以请你返回答案 模 mod 10^9 + 7 之后的结果即可。
示例 1:
输入:n = 5 输出:12 解释:举个例子,[1,2,5,4,3] 是一个有效的排列,但 [5,2,3,4,1] 不是,因为在第二种情况里质数 5 被错误地放在索引为 1 的位置上。
示例 2:
输入:n = 100 输出:682289015
提示:
1 <= n <= 100
解题思路
方法一:数学
先统计 范围内的质数个数,我们记为 。然后求 以及 阶乘的乘积得到答案,注意取模操作。
这里我们用“埃氏筛”统计质数。
如果 是质数,那么大于 的 的倍数 ,,… 一定不是质数,因此我们可以从这里入手。
设 表示数 是不是质数,如果是质数则为 ,否则为 。
我们在 范围内顺序遍历每个数 ,如果这个数为质数,质数个数增 ,然后将其所有的倍数 都标记为合数(除了该质数本身),即 ,这样在运行结束的时候我们即能知道质数的个数。
时间复杂度 。
class Solution:
def numPrimeArrangements(self, n: int) -> int:
def count(n):
cnt = 0
primes = [True] * (n + 1)
for i in range(2, n + 1):
if primes[i]:
cnt += 1
for j in range(i + i, n + 1, i):
primes[j] = False
return cnt
cnt = count(n)
ans = factorial(cnt) * factorial(n - cnt)
return ans % (10**9 + 7)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n log log n) using a sieve to count primes, plus O(n) for factorial computations. Space complexity is O(n) for the sieve and factorial storage. The dominant factor is prime counting and factorial computation. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Check if the candidate separates prime and composite numbers correctly.
- question_mark
Observe whether modulo operations are applied to avoid overflow.
- question_mark
Listen for explanations about factorial usage and arrangement counting.
常见陷阱
外企场景- error
Attempting to generate all permutations, which is computationally infeasible.
- error
Forgetting to apply modulo 10^9 + 7 during factorial multiplication.
- error
Misidentifying prime numbers, especially 1, which is not prime.
进阶变体
外企场景- arrow_right_alt
Compute valid arrangements where primes occupy only even indices instead of prime indices.
- arrow_right_alt
Find permutations for a given list of numbers instead of 1 to n following the prime arrangement pattern.
- arrow_right_alt
Return the lexicographically smallest valid permutation instead of counting all permutations.