一.问题描述
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.
Example 1:
Input: n = 5 Output: 12 Explanation: For example [1,2,5,4,3] is a valid permutation, but [5,2,3,4,1] is not because the prime number 5 is at index 1.
Example 2:
Input: n = 100 Output: 682289015
Constraints:
1 <= n <= 100
二.解决思路
其实就是找1~n有多少个质数,然后计算所有质数的全排列和所有非质数的全排列然后相乘求余
本身这个东西是比较简单的,
你可以一个个迭代判断每个数是不是质数,
但是求一定范围内质数个数的最快算法是(除了查表法)Sieve of Eratosthenes(埃拉托色泥筛选法)算法
其实根据定理:一个合数总是可以分解成若干个质数的乘积,那么如果把质数(最初只知道2是质数)的倍数都去掉,那么剩下的就是质数了。
所以我们可以从2开始一个个的把倍数都去掉,直到大于n为止。
给出两种实现
更多leetcode算法题解法请关注我的专栏leetcode算法从零到结束或关注我
欢迎大家一起套路一起刷题一起ac
三.源码
1.一个个的求是否是质数
from functools import reduce
import math
class Solution:
def numPrimeArrangements(self, n: int) -> int:
cnt_prime=0
for i in range(2,n+1):
is_prime=1
for t in range(2,int(math.sqrt(i))+1):
if i%t==0:
is_prime=0
break
cnt_prime+=is_prime
if cnt_prime!=0: # reduce函数用来求阶乘
per_prime=reduce(lambda x,y:x*y, range(1,cnt_prime+1))
else:per_prime=1
return (per_prime*(reduce(lambda x,y:x*y, range(1,n-cnt_prime+1))))%(pow(10,9)+7)
2.埃拉托色泥筛选法
from functools import reduce
class Solution:
def numPrimeArrangements(self, n: int) -> int:
is_prime=[1]*(n+1)
is_prime[0],is_prime[1],=0,0
p=2
while p*p<=n:
if is_prime[p]:
for t in range(p*p,n+1,p):
is_prime[t]=0
p+=1
cnt_prime=sum(is_prime)
if cnt_prime!=0:
per_prime=reduce(lambda x,y:x*y, range(1,cnt_prime+1))
else:per_prime=1
return (per_prime*(reduce(lambda x,y:x*y, range(1,n-cnt_prime+1))))%(10**9+7)
本文详细解析了一道关于质数排列的算法题,通过找出1至n范围内的质数数量,利用埃拉托色泥筛选法高效求解质数个数,并计算质数与非质数的全排列组合,最后对结果进行模运算。提供了两种实现方式,一种是逐个判断质数,另一种是使用埃拉托色泥筛选法。
433

被折叠的 条评论
为什么被折叠?



