当前位置:网站首页>【每日一题】1175. 质数排列
【每日一题】1175. 质数排列
2022-07-01 15:49:00 【王六六的IT日常】
感觉这方面的自己练的有点少。
做一个总结。。。
204. 计数质数
题目:
给定整数 n ,返回 所有小于非负整数 n 的质数的数量 。
质数的定义:在大于 1 的自然数中,除了 1 和它本身以外不再有其他因数的自然数。
- 枚举
class Solution {
public int countPrimes(int n) {
int ans = 0;
for (int i = 2; i < n; ++i) {
ans += isPrime(i) ? 1 : 0;
}
return ans;
}
public boolean isPrime(int x) {
for (int i = 2; i * i <= x; ++i) {
if (x % i == 0) {
return false;
}
}
return true;
}
}
- 埃氏筛:https://leetcode.cn/problems/count-primes/solution/nick-by-nickbean-6ej3/、https://leetcode.cn/problems/count-primes/solution/kuai-lai-miao-dong-shai-zhi-shu-by-sweetiee/
如果一个数A是质数,那么2A,3A,…,n*A一定不是质数
所以可以在[1,n]这个范围内,从最开始的2,3就开始给质数后面的数进行做初始化操作!
class Solution {
public int countPrimes(int n) {
int[] isPrime = new int[n];
//填充isPrime数组的每个元素都是1
Arrays.fill(isPrime, 1);
int count = 0;
for (int i = 2; i < n; ++i) {
if (isPrime[i] == 1) {
/** * 说明i是质数! */
count++;
if ((long) i * i < n) {
for (int j = i * i; j < n; j += i) {
isPrime[j] = 0;
}
}
}
}
return count;
}
}
这题还有更好的筛法——线性筛,但不属于笔试/面试范畴,不需要掌握。
- 线性筛
class Solution {
public int countPrimes(int n) {
List<Integer> primes = new ArrayList<Integer>();
int[] isPrime = new int[n];
Arrays.fill(isPrime, 1);
for (int i = 2; i < n; ++i) {
if (isPrime[i] == 1) {
primes.add(i);
}
for (int j = 0; j < primes.size() && i * primes.get(j) < n; ++j) {
isPrime[i * primes.get(j)] = 0;
if (i % primes.get(j) == 0) {
break;
}
}
}
return primes.size();
}
}
1175. 质数排列
[数学 + 质数 + 阶乘]
参考题解:https://leetcode.cn/problems/prime-arrangements/solution/1175-zhi-shu-pai-lie-java-100-by-wa-pian-bo17/
- [1,n]一共有多少个质数
- ans == 质数!* 非质数!
根据题意,可将问题转换为求 n 以内的质数个数,记为 a,同时可得非质数个数为 b = n - a。
质数的放置方案数为 a!,而非质数的放置方案数为 b!,根据「乘法原理」总的放置方案数为 a!×b!。
class Solution {
int mod = (int) 1e9 + 7;
public int numPrimeArrangements(int n) {
int prime = 0;
for (int i = 1; i <= n; i++) {
if (isPrime(i)) {
prime++;
}
}
long ans = factorial(prime);
ans *= factorial(n - prime);
return (int) (ans % mod);
}
//阶乘
private long factorial(int num) {
long ans = 1;
for (int i = 1; i <= num; i++) {
ans *= (long) i;
ans %= mod;
}
return ans;
}
private boolean isPrime(int num) {
if (num == 2) {
return true;
}
if (num == 1 || num % 2 == 0) {
return false;
}
for (int i = 3; i * i <= num; i += 2) {
if (num % i == 0 || i * i == num) {
return false;
}
}
return true;
}
}
参考:https://leetcode.cn/problems/prime-arrangements/solution/by-ac_oier-t3lk/
打表 + 二分 + 数学
可以通过「打表」的方式将 100 以内的质数预处理到数组 list 中,对于每个 n 而言,我们找到第一个满足「值小于等于 n」的位置,从而得知 n 范围以内的质数个数。
class Solution {
static int MOD = (int)1e9+7;
static List<Integer> list = new ArrayList<>();
static {
for (int i = 2; i <= 100; i++) {
boolean ok = true;
for (int j = 2; j * j <= i; j++) {
if (i % j == 0) ok = false;
}
if (ok) list.add(i);
}
}
public int numPrimeArrangements(int n) {
int l = 0, r = list.size() - 1;
while (l < r) {
int mid = l + r + 1 >> 1;
if (list.get(mid) <= n) l = mid;
else r = mid - 1;
}
int a = r + 1, b = n - a;
long ans = 1;
for (int i = b; i > 1; i--) ans = ans * i % MOD ;
for (int i = a; i > 1; i--) ans = ans * i % MOD ;
return (int)ans;
}
}
边栏推荐
- Pnas: brain and behavior changes of social anxiety patients with empathic embarrassment
- 6.2 normalization 6.2.6 BC normal form (BCNF) 6.2.9 normalization summary
- 自動、智能、可視!深信服SSLO方案背後的八大設計
- July 1, 2022 Daily: Google's new research: Minerva, using language models to solve quantitative reasoning problems
- The newly born robot dog can walk by himself after rolling for an hour. The latest achievement of Wu Enda's eldest disciple
- Smart Party Building: faith through time and space | 7.1 dedication
- Automatique, intelligent, visuel! Forte conviction des huit conceptions derrière la solution sslo
- [one day learning awk] function and user-defined function
- process. env. NODE_ ENV
- STM32F1与STM32CubeIDE编程实例-PWM驱动蜂鸣器生产旋律
猜你喜欢

三星率先投产3nm芯片,上海应届硕士生可直接落户,南开成立芯片科学中心,今日更多大新闻在此...

ATSs: automatically select samples to eliminate the difference between anchor based and anchor free object detection methods
![[pyGame practice] do you think it's magical? Pac Man + cutting fruit combine to create a new game you haven't played! (source code attached)](/img/0a/c1a4b57b9729e0cf9de1feae9f8c19.png)
[pyGame practice] do you think it's magical? Pac Man + cutting fruit combine to create a new game you haven't played! (source code attached)

process. env. NODE_ ENV

How does win11 set user permissions? Win11 method of setting user permissions

MySQL的零拷贝技术

工厂高精度定位管理系统,数字化安全生产管理

一次革命、两股力量、三大环节:《工业能效提升行动计划》背后的“减碳”路线图...

使用腾讯云搭建图床服务
![[200 opencv routines] 216 Draw polylines and polygons](/img/47/3e5564ff9cf5fa3ef98a2ea27694cf.png)
[200 opencv routines] 216 Draw polylines and polygons
随机推荐
Zhang Chi Consulting: household appliance enterprises use Six Sigma projects to reduce customers' unreasonable return cases
Samsung took the lead in putting 3nm chips into production, and Shanghai's fresh master students can settle directly. Nankai has established a chip science center. Today, more big news is here
最新NLP赛事实践总结!
Detailed explanation of stm32adc analog / digital conversion
Does 1.5.1 in Seata support mysql8?
[target tracking] |stark
Huawei issued hcsp-solution-5g security talent certification to help build 5g security talent ecosystem
Hardware development notes (9): basic process of hardware development, making a USB to RS232 module (8): create asm1117-3.3v package library and associate principle graphic devices
Pocket network supports moonbeam and Moonriver RPC layers
There will be a gap bug when the search box and button are zoomed
【Pygame实战】你说神奇不神奇?吃豆人+切水果结合出一款你没玩过的新游戏!(附源码)
Solution to the problem that the keypad light does not light up when starting up
电脑照片尺寸如何调整成自己想要的
微服务追踪SQL(支持Isto管控下的gorm查询追踪)
Go language learning notes - Gorm use - table addition, deletion, modification and query | web framework gin (VIII)
MySQL advanced 4
Crypto Daily: Sun Yuchen proposed to solve global problems with digital technology on MC12
Trace the source of drugs and tamp the safety dike
【LeetCode】43. 字符串相乘
process.env.NODE_ENV