筛法区分质数合数

原题:

Write a program to read in a list of integers and determine whether or not each number is prime. A number, n, is prime if its only divisors are 1 and n. For this problem, the numbers 1 and 2 are not considered primes. 
InputEach input line contains a single integer. The list of integers is terminated with a number<= 0. You may assume that the input contains at most 250 numbers and each number is less than or equal to 16000. 
OutputThe output should consists of one line for every number, where each line first lists the problem number, followed by a colon and space, followed by "yes" or "no". 
Sample Input
1
2
3
4
5
17
0
Sample Output
1: no
2: no
3: yes
4: no
5: yes
6: yes
解:


#include<iostream>

#include<cstring>

#include<cmath>

#define N 16000

using namespace std;

bool isprime[16005];//0为质数,1为合数

int pri[16005];

void prime()

{

    int cnt=1;

    memset(pri,0,sizeof(pri));

    memset(isprime,0,sizeof(isprime));

    isprime[1]=1;

    for(int i=2;i<=sqrt(N);i++)//从2开始筛选,倍数都为合数

    {

        if(!isprime[i])//如果是质数(0取反==1 进入if 存储数值为0)

        {

            pri[cnt++]=i;//储存质数(本题无用)

            for(int j=i*2;j<=N;j+=i)//从2*i开始递推 每次增加i

            {

                isprime[j]=1;//

            }

        }

    }

    isprime[2]=1;//若开始就对2赋值则到时无法进入if 

}

int main()

{

    prime();

    int t=250;

    for(int i=1;i<=t;i++)

    {

        int k;

        cin>>k;

        if(k>0)

        {

            if(isprime[k]==0) cout<<i<<": "<<"yes"<<endl;

            else cout<<i<<": "<<"no"<<endl;

        }

        else break;

    }


}



猜你喜欢

转载自blog.csdn.net/qq_41660465/article/details/79129642