当前位置:网站首页>Acwing 866. determining prime numbers by trial division
Acwing 866. determining prime numbers by trial division
2022-07-25 21:57:00 【_ Liu Xiaoyu】
Given n A positive integer ai, Determine whether each number is a prime number .
Input format
The first line contains integers n.
Next n That's ok , Each line contains a positive integer ai.
Output format
common n That's ok , Among them the first i Line output the i A positive integer ai Is it a prime number , Yes, output Yes, Otherwise output No.
Data range
1≤n≤100,
1≤ai≤231−1
sample input :
2
2
6
sample output :
Yes
No
Method 1: Direct violence enumeration O(n2)
But higher requirements will lead to overtime
bool is_prime(int n)
{
if(n < 2) return false;
for(int i=2; i <= n; i++)
if(n % i == 0)
return false;
return true;
}
Optimization idea : You only need to traverse half
because d|n when , n/d|n It's OK ; among d Representation factor ,n It means a number , | To divide or divide
Put it in order : d <= n/d that will do ; have to d * d <= n that will do ,
so , When looking for factors , Just traverse the root n Part can be
Method 2: Use it directly sqrt function
bool is_prime(int n){
if(n < 2) return false; //2 Is the smallest prime number , If n Less than 2, that n It must not be a prime number
for(int i = 2;i <= sqrt(n);i ++){
// Optimization part
if(n % i == 0){
// If it can be i to be divisible by , This number is not prime
return false; // Return no
}
}
return true; // Return is
}
however , This sqrt The bottom layer of the function runs very slowly , Every time this line of code is executed , Need to calculate once , Let's look at other methods
Method 3:
Optimize the traversal code to for(int i = 2;i * i <= n;i ++), Basically, it is similar to the above , But there may be a risk of overflow , Not recommended
Method 4:
Optimize the traversal code to for(int i=2; i <= n / i; i++), The principle is the same as above , But there is no risk of data overflow , This is recommended
Recommended method complete code
#include <iostream>
using namespace std;
// Trial division
// take O(n) Down to O(sqrt(n))
bool is_prime(int n)
{
if(n < 2) return false;
// for(int i=2; i * i <= n; i++) // There may be spillover risk
// for(int i=2; i <= sqrt(n); i++) // sqrt Every time the function calculates , Affect efficiency
for(int i=2; i <= n / i; i++) // Just judge the smaller divisor of the two
if(n % i == 0)
return false;
return true;
}
int main()
{
int m;
cin >> m;
while(m --)
{
int c;
cin >> c;
if(is_prime(c)) puts("Yes");
else puts("No");
}
return 0;
}
边栏推荐
- Oxford University: many common insomnia drugs lack long-term safety data
- [redis underlying parsing] string type
- C语言游戏 双缓存解决闪屏问题 详细总结[通俗易懂]
- [dinner talk] those things that seem to be for the sake of the company but are actually incomprehensible (2: soft quality "eye edge" during interview)
- 5、 Pinda general permission system__ PD tools XXS (anti cross site script attack)
- C语言:随机生成数+冒泡排序
- Redis configuration
- Naming rules for BSP of Quanzhi chip
- 【Flink】FLink RocksDBListState 报错 You cannot add null to a ListState
- How to solve the problem of using the download Plug-in for export?
猜你喜欢

少儿编程 电子学会图形化编程等级考试Scratch一级真题解析(判断题)2022年6月
![[Flink] flick rocksdbliststate reports an error you cannot add null to a liststate](/img/c0/1923e17f166ab4bc7d20f48398f366.jpg)
[Flink] flick rocksdbliststate reports an error you cannot add null to a liststate

信息安全建设原则指导

ORIGYN基金会正式启动$OGY Staking,引领新一轮生态利好

How to implement distributed locks with redis?

【leetcode天梯】链表 · 876 查找链表中间结点

5、 Pinda general permission system__ PD tools XXS (anti cross site script attack)

【GO基础02】第一个程序

C#Socket

GPON introduction and Huawei OLT gateway registration and configuration process
随机推荐
[MAIXPY]kpu: load error:2005, ERR_ READ_ File: read file failed problem solving
[redis underlying parsing] string type
【饭谈】那些看似为公司着想,实际却让人无法理解的事(二:面试时的软素质“眼缘”)
zigbee开发板(nxpzigbee开发)
Naming rules for BSP of Quanzhi chip
如何用 Redis 实现分布式锁的?
FAW red flag "King fried" is listed, which is safe and comfortable
New maixhub deployment (v831 and k210)
Children's programming electronic society graphical programming level examination scratch level 1 real problem analysis (judgment question) June 2022
Six principles of C program design
ansible+Crontab批部署巡检
Create files, file permissions, ownership, and sticky bits
The reisson distributed lock renewal failed due to network reasons, resulting in the automatic release of the lock when the business is still executing but the lock is not renewed.
Pyg tutorial (8): calculate a more efficient sparse matrix form
Redis为何选择单线程?
选择的能力
Babbitt | metauniverse daily must read: the popularity of virtual people has decreased, and some "debut is the peak", and the onlookers have dispersed
【饭谈】细说:下克上,向上管理,向上画饼。
【饭谈】软件测试薪资层次和分段(修仙)
五种分配方式是否会产生内部碎片、外部碎片