求素数

题目描述

(再次申明:本上机题全部由程序自动评判对错,所以没有要求的输出请一定不要出现,具体参照样例输入和输出即可)

输入两个正整数a、b,找出[a, b]之间的素数,由小到大输出。(2 <= a <= b <=1000000)

输入描述

每一行输入两个正整数,两数之间有一个空格,可能有多行输入!

tips:利用while(cin>>a>>b)语句实现循环输入变量

输出描述

输出[a,b]之间的素数,素数之间用一个空格隔开,每个输出占一行

样例输入

2 5
3 11

样例输出

2 3 5
3 5 7 11
#include <iostream>
using namespace std;

int main()
{
    bool q[1000001];
    for (int i = 0; i < 1000001;i++)
        q[i] = true;
    for (int d = 2;d * d <= 1000000; d++)
    {
        if(q[d])
        {
            for(int s = d * d;s <= 1000000; s+=d)
                q[s] = false;
        }
    }
    int a, b;
    while (cin >> a >> b)
    {
        int g = 0;
        for (int i = a; i <= b; i++)
        {
            if (q[i])
            {
            if (!g)
            {
                cout << i;
                g = 1;
            }
            else 
                cout << ' ' << i;
            }
       }
       cout << endl;
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/Zhz0306/p/8967638.html
今日推荐