当前位置:网站首页>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

边栏推荐
- Lldp compatible CDP function configuration
- BFS realizes breadth first traversal of adjacency matrix (with examples)
- C# 计算农历日期方法 2022
- AI 从代码中自动生成注释文档
- 「笔记」折半搜索(Meet in the Middle)
- Your cache folder contains root-owned files, due to a bug in npm ERR! previous versions of npm which
- Maidong Internet won the bid of Beijing life insurance to boost customers' brand value
- [signal and system]
- Receive user input, height BMI, BMI detection small business entry case
- [100 cases of JVM tuning practice] 05 - Method area tuning practice (Part 2)
猜你喜欢

Byte P7 professional level explanation: common tools and test methods for interface testing, Freeman

pytorch之数据类型tensor

"Exquisite store manager" youth entrepreneurship incubation camp - the first phase of Shunde market has been successfully completed!

系统休眠文件可以删除吗 系统休眠文件怎么删除

JTAG debugging experience of arm bare board debugging

c语言—数组

如何管理分布式团队?
![[batch dos-cmd command - summary and summary] - string search, search, and filter commands (find, findstr), and the difference and discrimination between find and findstr](/img/4a/0dcc28f76ce99982f930c21d0d76c3.png)
[batch dos-cmd command - summary and summary] - string search, search, and filter commands (find, findstr), and the difference and discrimination between find and findstr

黑马笔记---异常处理

Installation of gazebo & connection with ROS
随机推荐
pytorch之数据类型tensor
UI控件Telerik UI for WinForms新主题——VS2022启发式主题
Dark horse notes - exception handling
[case sharing] basic function configuration of network loop detection
Installation of gazebo & connection with ROS
JTAG debugging experience of arm bare board debugging
[hfctf2020]babyupload session parsing engine
[Niuke] [noip2015] jumping stone
子网划分、构造超网 典型题
SuperSocket 1.6 创建一个简易的报文长度在头部的Socket服务器
Asset security issues or constraints on the development of the encryption industry, risk control + compliance has become the key to breaking the platform
黑马笔记---异常处理
Tensorflow GPU installation
前置机是什么意思?主要作用是什么?与堡垒机有什么区别?
ClickHouse字段分组聚合、按照任意时间段粒度查询SQL
HMM 笔记
资产安全问题或制约加密行业发展 风控+合规成为平台破局关键
如何管理分布式团队?
Pytorch中torch和torchvision的安装
1123. 最深叶节点的最近公共祖先