section 1.5 sprime

来源:互联网 发布:java api有手机版的吗 编辑:程序博客网 时间:2024/05/12 18:21

-这道题和section 1.5 pprime思路几乎一模一样
-质数验证函数分了两类,num<=10000和num>=10000

"YOUR PROGRAM ('sprime') WORKED FIRST TIME!  That's fantastic and a rare thing.  Please accept these special automatedcongratulations."
/*ID: penglin3PROG: sprimeLANG: C++11*/#include <iostream>#include <fstream>#include <vector>#include <math.h>using namespace std;//fstream 需要std合法范围bool bPrime[10001]{};vector<int> viPrime{};vector<long> answer{};#define min(a , b) ((a < b) ? a : b)//建质数表的函数,然后写入bPrime,vbPrimevoid listPrime(bool *bPrime,vector<int> &viPrime, const int& maxnum);//判断是否为素数bool judgePrime(const bool *bPrime,const vector<int>&viPrime, const long& num);//生成Superprime n当前位数,N总位数,sp是生成的数void Superprime(const int& n, const int& N,const long sp, void f(long sp));//处理superprime的函数;void f(long sp);int main() {    ifstream fin("sprime.in");    ofstream fout("sprime.out");    int N;    fin >> N;    //处理    listPrime(bPrime, viPrime, pow(10, min(4, N)));    Superprime(1, N, 0, f);    //输出    for (auto &itan : answer)        fout << itan << endl;    fin.close();    fout.close();    return 0;}//建质数表的函数,数n:3,5,7...maxnum数组最大下标,然后写入vbPrimevoid listPrime(bool *bPrime,vector<int> &viPrime, const int& maxnum) {    bPrime[0] = true;    bPrime[1] = true;    for (int i = 4; i <= maxnum; i += 2 ) {        bPrime[i] = true;    }    int n = 3;    while (n * n < maxnum) {        for (int i = n * n; i <= maxnum; i += n) {                bPrime[i] = true;            }        do//这里必须用do-while            n += 2;        while (n * n < maxnum && bPrime[n]);    }    for (int i = 2; i <= maxnum; ++i)        if (i % 2 && !bPrime[i]) viPrime.push_back(i);    return;}/*---------------------------------------------------------*///判断是否为素数bool judgePrime(const bool *bPrime,const vector<int>&viPrime, const long& num) {    if (num <= 10000) {        return !(bPrime[num]);    }    else {        for (int i = 0; i != viPrime.size(); ++i) {            if (viPrime[i] > sqrt(num)) break;            else if (!(num % viPrime[i]))return false;        }        return true;    }}/*---------------------------------------------------------*///生成Superprime n当前位数,N总位数,sp是生成的数void Superprime(const int& n,const int& N, const long sp, void f(long sp)) {    if (n == 1) {        int i = 2;        Superprime(n + 1, N, i, f);        for (i = 3; i <= 7; i += 2) {            Superprime(n + 1, N, i, f);        }    }    else if (n <= N) {        long sp2 = 0;        for (int i = 1; i <= 9; i += 2) {            sp2 = i + sp*10;            if (judgePrime(bPrime, viPrime, sp2)) Superprime(n + 1, N, sp2, f);        }    }    else {        f(sp);    }    return;}//处理superprime的函数;void f(long sp) {    answer.push_back(sp);}
0 0
原创粉丝点击