题解 | #素数#

素数

http://www.nowcoder.com/practice/7f4be54b37a04fdaa4ee545819151114

#include<iostream>
#include<cmath>

using namespace std;
const int N = 10010;

bool isPrime(int n)
{
    if(n <= 1) return false;
    for(int i = 2; i <= sqrt(n); i ++)
    {
        if(n % i == 0) return false;
    }
    return true;
}

bool st[N];
int primes[N], cnt;
void get_primes(int n)
{
    for(int i = 2; i <= n; i ++)
    {
        if(st[i]) continue;
        primes[cnt ++] = i;
        for(int j = i + i; j <= n; j += i)
            st[j] = true;
    }
}

int main()
{
    int n;
    get_primes(N);
    while(cin >> n)
    {
        bool isFirst = true, find = false;
        for(int i = 1; i < n; i ++) {
            if(primes[i] < n && primes[i] % 10 == 1) {
                find = true;
                if(isFirst) {
                    cout << primes[i];
                    isFirst = false;
                }
                else {
                    cout << " " << primes[i];
                }
            }
        }
        if(!find) cout << "-1" << endl;
    }
    return 0;
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务