当前位置:网站首页>LeetCode:1175. 质数排列
LeetCode:1175. 质数排列
2022-07-06 17:39:00 【Vicky__3021】
题目:
1175. 质数排列
请你帮忙给从 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
解析:
n为1或2时,返回值为1。当n大于2时,通过遍历整除判断该数是否为质数,如果某个数可以整除i,那么i为合数。
代码:
class Solution:
def numPrimeArrangements(self, n: int) -> int:
count1 = 1 # 合数数量
count2 = 1 # 质数数量
ans = 1
if n == 1 or n == 2:
return 1
for i in range(3, n+1):
for j in range(2, i):
if i % j == 0:
count1 += 1
ans = ans * count1 % (7 + 10**9)
break
else:
count2 += 1
ans = ans * count2 % (7 + 10**9)
return ans

边栏推荐
- Oracle:CDB限制PDB资源实战
- Anfulai embedded weekly report no. 272: 2022.06.27--2022.07.03
- Your cache folder contains root-owned files, due to a bug in npm ERR! previous versions of npm which
- MySQL中回表的代价
- Force buckle 1037 Effective boomerang
- Using the entry level of DVA in taro3.*
- Pytorch中torch和torchvision的安装
- 【案例分享】网络环路检测基本功能配置
- Taro2.* applet configuration sharing wechat circle of friends
- Make Jar, Not War
猜你喜欢

微信公众号发送模板消息

Niuke cold training camp 6B (Freund has no green name level)

Anfulai embedded weekly report no. 272: 2022.06.27--2022.07.03

Tensorflow GPU installation

AI 从代码中自动生成注释文档

Maidong Internet won the bid of Beijing life insurance to boost customers' brand value

Installation of gazebo & connection with ROS

2022 Google CTF SEGFAULT LABYRINTH wp

Lldp compatible CDP function configuration

动态规划思想《从入门到放弃》
随机推荐
C language - array
golang中的atomic,以及CAS操作
实现mysql与ES的增量数据同步
Dark horse notes - create immutable sets and streams
[case sharing] basic function configuration of network loop detection
UI control telerik UI for WinForms new theme - vs2022 heuristic theme
Make Jar, Not War
golang中的WaitGroup实现原理
gnet: 一个轻量级且高性能的 Go 网络框架 使用笔记
The MySQL database in Alibaba cloud was attacked, and finally the data was found
Your cache folder contains root-owned files, due to a bug in npm ERR! previous versions of npm which
The difference between spin and sleep
Taro2.* 小程序配置分享微信朋友圈
Neon Optimization: an optimization case of log10 function
[JS] obtain the N days before and after the current time or the n months before and after the current time (hour, minute, second, year, month, day)
2022 Google CTF SEGFAULT LABYRINTH wp
线段树(SegmentTree)
Neon Optimization: summary of performance optimization experience
[100 cases of JVM tuning practice] 04 - Method area tuning practice (Part 1)
微信公众号发送模板消息