线性筛——素数
优点:相较于我们所学的基础算法一层一层不断除,线性筛减少了许多不必要的运算(不过我认为单个数字判断并不能显现其优势,线性筛在多组数据判断中优势极为明显)
原理:素数的定义是不可以被除1和它本身整除的数。so我们可以通过把每个数的倍数都标记下来,没有被标记的自然就是素数,***这个其中有一点非常关键就是被标记的数字我们就不用管它倍数了,这也提升的速度 (关键)***owo.
接下来上题目,以代码为灵魂
Everybody knows any number can be combined by the prime number.
Now, your task is telling me what position of the largest prime factor.
The position of prime 2 is 1, prime 3 is 2, and prime 5 is 3, etc.
Specially, LPF(1) = 0.
Input
Each line will contain one integer n(0 < n < 1000000).
Output
Output the LPF(n).
Sample Input
1
2
3
4
5
Sample Output
0
1
2
1
3
知道你可能看不懂所以翻译软件闪亮登场(其实是我看不懂)
大家都知道任何数都可以被质数组合。
现在,你的任务是告诉我最大质因数的位置。
质数2的位置是1,质数3的位置是2,质数5的位置是3,等等。
特别地,LPF(1) = 0。
输入
每一行将包含一个整数n(0 < n < 1000000)。
#include<bits/stdc++.h>
using namespace std;
#define max 1000010
int pri[max];
void jud()//这一块就是所谓的线性筛的体现了
{
memset(pri,0,sizeof(pri));//初始化,建议大家习惯初始化qwq
int mark=0;
for(int i=2;i<max;i++)
{
if(pri[i]==0)//证明他不是其他数字的倍数
{
mark++;//标注位置
for(int bi=i;bi<max;bi+=i)//倍数增加
{
pri[bi]=mark;
}
}
}
}
int main()
{
int s;
jud();
while(scanf("%d",&s)!=EOF)
{
printf("%d\n",pri[s]);
}
return 0;
}
结束啦