当前位置:网站首页>埃氏筛选法:统计素数个数
埃氏筛选法:统计素数个数
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本身为倍数进行递增,提高效率。
边栏推荐
猜你喜欢
Simulation of Water Temperature Control System Based on Fuzzy PID Controller
Error when source install/setup.bash
小黑leetcode之旅:94. 二叉树的中序遍历(补充Morris 中序遍历)
角度和弧度的相互换算
Word怎么制作双面席卡?使用Word制作双面席卡方法
别叫我玩,我要考PMP:考PMP选择机构需要了解的那些事儿
微软word怎么转换成pdf文件?微软word转换为pdf格式的方法
线段相交的应用
fixed investment fund
普源精电上半年扭亏为盈,高端产品持续发力!你看好仪器界“华为”吗?
随机推荐
Next second data: the transformation of the modern data stack brought about by the integration of lake and warehouse has begun
MySQL Notes-06 Basic SQL Operations
Cookie、session、token
What are the benefits of enterprise data integration?How do different industries solve the problem of data access?
L3-2 至多删三个字符 (30 分)
URL Protocol web page to open the application
别叫我玩,我要考PMP:考PMP选择机构需要了解的那些事儿
Application of Acrel5000web Energy Consumption System in a College-Susie Week
MySQL慢查询的多个原因
2021(ICPC)亚洲区域赛昆明站(CGHIJLM)
[Essay] To the friends of the 19th issue
leetcode:数组中的第K个最大元素
Word怎么制作双面席卡?使用Word制作双面席卡方法
fixed investment fund
浅谈Numpy中的shape、reshape函数的区别
Install Mysql8.0 on windos, and solve the problem of re-login exception ERROR 1045 (28000)
Unity2D_线框材质
How are data integration APIs key to enterprise digital transformation?
抽象类 or 接口
Ali Ermi: Without accept, can a TCP connection be established?