当前位置:网站首页>埃氏筛选法:统计素数个数
埃氏筛选法:统计素数个数
2022-08-09 21:35:00 【哆啦k梦0219】
埃筛法的核心思想:当我们找到一个素数,那么这个数小于n的所有倍数肯定都不是素数,同时进行标记。
#include <iostream>
using namespace std;
class Solution {
public:
bool isprime(int n)
{
for (int i = 2; i*i <= n; i++)
{
if (n % i == 0)
return false;
}
return true;
}
int cout_prime(int n)
{
int* tag = new int[n] {0};//0代表是素数
int count = 0;
for (int i = 2; i < n; i++)
{
if (tag[i]==0)
{
count++;
for (int j = i * i; j < n; j += i)//j+=i实现i的递增
{
tag[j] = 1;
}
}
}
return count;
}
};
int main()
{
Solution s;
int n = s.cout_prime(100);
cout << n;
return 0;
}
以上代码中重点看这段代码:
for (int j = i * i; j < n; j += i)//j+=i实现i的递增
{
tag[j] = 1;
}
这段代码原版是j = i*2;但由于每次i对递增会出现重复标记的情况,故对代码进行优化,每次以i本身为倍数进行递增,提高效率。
边栏推荐
- 微软Excel表格点击单元格行和列都显示颜色怎么弄?聚光灯效果设置
- Interviewer: How to deal with Redis big key?
- 抽象类 or 接口
- Word第一页不要页眉怎么设置?设置Word首页不要页眉方法教程
- 【双链表增删查改接口的实现】
- LED闪烁 闪灯芯片IC 手电筒IC 闪灯控制IC 闪烁IC流水灯
- Hessian Matrix 海森矩阵
- Definition and Basic Operations of Linear Tables
- URL Protocol web page to open the application
- poj 3070 Fibonacci(简单矩阵连乘)
猜你喜欢
QGIS编译SIP的问题
Word怎么制作一张标准的答题卡?
DSPE-PEG-PDP, DSPE-PEG-OPSS, phospholipid-polyethylene glycol-mercaptopyridine reduce the immunogenicity of peptides
Unity2D_线框材质
在VMware上安装win虚拟机
必看设计干货|易知微设计师是怎么做标准可视化设计服务的?
Can I make a TCP connection without accept?
matlab neural network ANN classification
How are data integration APIs key to enterprise digital transformation?
Install Mysql8.0 on windos, and solve the problem of re-login exception ERROR 1045 (28000)
随机推荐
supervisor 命令操作大全「建议收藏」
【随笔】致19期的小伙伴们
威纶通触摸屏制作自定义弹出窗口的具体方法(3种)
上海控安SmartRocket系列产品推介(三):SmartRocket iVerifier计算机联锁系统验证工具
hdu 1503 Advanced Fruits(最长公共子序列的应用)
字符串哈希(2014 SERC J题)
【Efficient Tools】Remote Control Software ToDesk (Favorites)
Cholesterol-PEG-Thiol, CLS-PEG-SH, Cholesterol-PEG-Sulfhydryl for improved solubility
RHEL7系统修复rm -rf /boot /etc/fstab
kvm虚拟机出现启动不了,NOT available,PV大于分区
Word怎么制作双面席卡?使用Word制作双面席卡方法
SecureCRT强制卸载
DSPE-PEG-PDP, DSPE-PEG-OPSS, phospholipid-polyethylene glycol-mercaptopyridine reduce the immunogenicity of peptides
Can I make a TCP connection without accept?
LeetCode Daily Question (321. Create Maximum Number)
浅谈Numpy中的shape、reshape函数的区别
knn到底咋回事?
mysql多表左链接查询
Byte side: Can TCP and UDP use the same port?
Unity_物体自转