质数筛法(C++)

算法解释

大于等于5的质数一定和6的倍数相邻

令x≥1,将大于等于5的自然数表示如下:
··· 6x-1,6x,6x+1,6x+2,6x+3,6x+4,6x+5,6(x+1),6(x+1)+1 ···
可以看到,不在6的倍数两侧,即6x两侧的数为6x+2,6x+3,6x+4,由于2(3x+1),3(2x+1),2(3x+2),
所以它们一定不是素数,再除去6x本身,显然,素数要出现只可能出现在6x的相邻两侧
因此 当 x > 5 时, 质数一定出现在 6x -1 和 6x + 1 两序列之内

参考代码

#include <iostream>
#include <cstdio>
#include <cmath>

using namespace std;

int N,M;
 
bool prime(int ans)
{
    
    
    if(ans==1) return false;
    if(ans == 2||ans == 3) return true;
    if(ans == 4)  return false;
    
    if(ans%6 != 1 && ans%6 != 5) return false;
    
    int temp = sqrt(ans);
    
    for(int i = 5;i<=temp;i+=6)
    {
    
    
        if(ans%i==0||ans%(i+2)==0)
        {
    
    
            return false;
        }
    }
    
    return true;
}
int main()
{
    
    
   // freopen("test.in","r",stdin);
    
    int a;
    
    cin >> N >> M;
    
    for(int i = 0;i<M;i++)
    {
    
    
        cin >> a;
        if(prime(a)==true)
        {
    
    
            cout << "Yes"<<'\n';
        }
        else
        {
    
    
            cout << "No"<<'\n';
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_39592312/article/details/109104876