sgu 113

1. 线性素数筛
2. 对于一个数n的所有因子对(a,b), a 必定小于等于sqrt(n)
3. 暴力法

#include <cstdio>
#include <vector>
#include <cmath>
using namespace std;


vector<int> primeList;
vector<char> isPrime;

const int NOT_A_PRIME = '\0';
const int IS_A_PRIME = '\1';

int selectPrime(int limit) {
    int k;
    int i;

    primeList.resize(0);
    primeList.push_back(2);
    isPrime.resize(limit + 2);
    for (i = 0; i < isPrime.size(); ++i) isPrime[i] = IS_A_PRIME;
    isPrime[2] = IS_A_PRIME;

    for (i = 2; i <= limit; ++i) {
        if (isPrime[i]) primeList.push_back(i);
        for (k = 0; k < primeList.size(); ++k) {
            int cur = primeList[k] * i;
            if (cur > limit) break;
            isPrime[cur] = NOT_A_PRIME;
            if (i % primeList[k] == 0) break;
        }

    }
}

bool isPrimeForce(int n) {
    if (n <= primeList[primeList.size()-1]) return isPrime[n] == IS_A_PRIME;

    int sq = (int)floor(sqrt(n));
    int i;
    for (i = 0; i < primeList.size() && primeList[i] <= sq; ++i) {
        if (n % primeList[i] == 0) return false;
    }
    return true;
}



bool isNearlyPrime(int n) {
    int sq = (int)floor(sqrt(n));
    int i;
    for (i = 0; i < primeList.size() && primeList[i] <= sq; ++i) {
        if (n % primeList[i] == 0) {
            if (isPrimeForce(n / primeList[i])) return true;
            else return false;
        }
    }

    return false;
}


int main() {
    selectPrime(1000000);
    int N;
    scanf("%d", &N);
    int i;
    int x;
    for (i = 0; i < N; ++i) {
        scanf("%d", &x);
        if (isNearlyPrime(x)) printf("Yes\n");
        else printf("No\n");
    }
    return 0;
}


你可能感兴趣的:(sgu 113)