c++ 求N次方素数的快速方法

vfh0ocws  于 2023-02-20  发布在  其他
关注(0)|答案(4)|浏览(153)

我最近试图通过我的书中的100个不同的练习列表,这是目前的第23号。找到第N个素数,虽然这似乎很容易,我注意到它需要很长的时间来搜索更大的数字(又名50000需要大约47秒已经。

#include <iostream>
#include <time.h>

using namespace std;
bool checkPrime(int n);

int main()
{   
    while (true)
    {       
        register int number;
        cin >> number;
        register int counter = 0;
        register int numbers = 0;
        time_t start = clock();
        while (counter < number)
        {
            numbers++;
            if (checkPrime(numbers))counter++;
        }
        double time_diff = (clock() - start);
        cout << numbers << endl;
        cout << "Time needed to process in ms: " << time_diff << endl;
    }
}

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

这是代码本身,没有什么太花哨,因为它仍然是一个比较容易的练习,尝试设置变量作为一个寄存器,因为我听说它有时会使事情更快。Wolfram Alpha需要大约10秒来检查第100.000个素数,我的代码在这里需要大约90。提前感谢,Folling

vxf3dgd4

vxf3dgd41#

如果没有空间限制,请创建一个包含质数的向量,并按如下所示更改checkPrime方法:

vector<int> primes;
bool checkPrime(int n) {
     if (n <= 1) return false;
     for (int i = 0; i < primes.size(), primes.at(i) <= sqrt(n); i++) {

          if (n%primes.at(i)== 0)
               return false;
     }
     primes.push_back(n)
     return true;
}

通过这种方法,你只需要检查n是否能被一个素数整除,而不是检查所有的数字直到它的平方根。
在这里,我们利用了一个数要么是素数,要么是一个或多个素数的倍数。
CheckPrime方法是O(log n),因此查找前N个素数是O(n log n),其中n是第N个素数的值

4si2a6ki

4si2a6ki2#

试试这个:

#include <iostream>
#include <time.h>
#include <vector>
#include <math.h>

using namespace std;
inline bool checkPrime(int n,std::vector<int>);

int main()
{
    int number,counter,numbers;
    std:cout<<"Prime Searcher";
    std::vector<int> sieve;

    while (true)
    {

        cin >> number;
        counter = 0;
        numbers = 0;
        time_t start = clock();
        while (counter < number)
        {
            if (numbers>2){
                numbers+=2;
            }
            else{
                numbers++;
            }
            if (checkPrime(numbers,sieve)){
                sieve.push_back(numbers);
                counter++;
            }

            }
        double time_diff = (clock() - start);
        cout << numbers << endl;
        cout << "Time needed to process in seconds: " << time_diff/CLOCKS_PER_SEC << endl;
    }
}

inline bool checkPrime(int n, std::vector<int> sieve) {
    double numPrimes=(sqrt(n)/log(sqrt(n))+3);
    if (numPrimes>sieve.size()){numPrimes=sieve.size();}
    if (n <= 1) return false;
    for (int i = 2; i < numPrimes; i++) {
        if (n%sieve[i] == 0)return false;
    }
    return true;
}

根据我的基准测试,对于n = 4000,这是一个超过2倍的优化,并且随着数字的增加而增加。register是贬值的。任何关于如何进一步优化的建议将是感激的。在n = 50000,在我的机器上需要24秒。

axr492tv

axr492tv3#

这是一个很好的方法为您的演习和非常大的数字

bool chekPrime(unsigned long long int n){
int flag=0;            //flag=0 => flag is not set
if(n<=1||n%2==0)flag=1;//flag=1 => n is not prime
if(n==2||n==3)flag=2;  //flag=2 => n is prime
if(flag==0){
    for(unsigned long long int i=3;i*i<=n;i+=2){
        if(n%i==0){
            flag=1;//flag=1 => n is not prime
            break;
        }
    }
}
//if flag not set or flag=2 => n is prime
if(flag==0||flag==2)return true;
else return false;

}

pzfprimi

pzfprimi4#

如果你需要的第n个素数计算它非常快。这个代码为你两个算法用于此
1.第一个算法是Meisel-Lehmer(Meisel-Lehmer非常快速地计算从1到n的素数计数)
1.第二种算法是二分查找

#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
const int N = 1e6 + 2;
bool np[N];
int prime[N], pi[N];

int getprime() {
    int cnt = 0;
    np[0] = np[1] = true;
    pi[0] = pi[1] = 0;
    for (int i = 2;i < N;++i) {
        if (!np[i]) prime[++cnt] = i;
        pi[i] = cnt;
        for (int j = 1;j <= cnt && i * prime[j] < N;++j) {
            np[i * prime[j]] = true;
            if (i % prime[j] == 0) break;
        }
    }
    return cnt;
}
const int M = 7;
const int PM = 2 * 3 * 5 * 7 * 11 * 13 * 17;
int phi[PM + 1][M + 1], sz[M + 1];
void init() {
    getprime();
    sz[0] = 1;
    for (int i = 0;i <= PM;++i) phi[i][0] = i;
    for (int i = 1;i <= M;++i) {
        sz[i] = prime[i] * sz[i - 1];
        for (int j = 1;j <= PM;++j) {
            phi[j][i] = phi[j][i - 1] - phi[j / prime[i]][i - 1];
        }
    }
}
int sqrt2(long long x) {
    long long r = (long long)sqrt(x - 0.1);
    while (r * r <= x) ++r;
    return int(r - 1);
}
int sqrt3(long long x) {
    long long r = (long long)cbrt(x - 0.1);
    while (r * r * r <= x) ++r;
    return int(r - 1);
}
long long getphi(long long x, int s) {
    if (s == 0) return x;
    if (s <= M) return phi[x % sz[s]][s] + (x / sz[s]) * phi[sz[s]][s];
    if (x <= prime[s] * prime[s]) return pi[x] - s + 1;
    if (x <= prime[s] * prime[s] * prime[s] && x < N) {
        int s2x = pi[sqrt2(x)];
        long long ans = pi[x] - (s2x + s - 2) * (s2x - s + 1) / 2;
        for (int i = s + 1;i <= s2x;++i) {
            ans += pi[x / prime[i]];
        }
        return ans;
    }
    return getphi(x, s - 1) - getphi(x / prime[s], s - 1);
}
long long getpi(long long x) {
    if (x < N) return pi[x];
    long long ans = getphi(x, pi[sqrt3(x)]) + pi[sqrt3(x)] - 1;
    for (int i = pi[sqrt3(x)] + 1, ed = pi[sqrt2(x)];i <= ed;++i) {
        ans -= getpi(x / prime[i]) - i + 1;
    }
    return ans;
}
long long lehmer_pi(long long x) {
    if (x < N) return pi[x];
    int a = (int)lehmer_pi(sqrt2(sqrt2(x)));
    int b = (int)lehmer_pi(sqrt2(x));
    int c = (int)lehmer_pi(sqrt3(x));
    ll sum = getphi(x, a) + ll((b + a - 2) * (b - a + 1)) / 2;
    for (int i = a + 1;i <= b;i++) {
        ll w = x / prime[i];
        sum -= lehmer_pi(w);
        if (i > c) continue;
        ll lim = lehmer_pi(sqrt2(w));
        for (int j = i;j <= lim;j++) {
            sum -= lehmer_pi(w / prime[j]) - (j - 1);
        }
    }
    return sum;

}

//32000000000 ---1382799415 count
//25000000000 ---1091987405 count
//23000000000 ---1008309544 count
int main() {
    init();
    ios_base::sync_with_stdio(false);
    cin.tie(0);cout.tie(0);
    long long n, l, r, res = 0;
    cin >> n;
    l = n;
    if (n == 1)cout << 2;
    else {
        l = 2;
        r = 23000000000;
        while (l < r) {
            ll k = (l + r) / 2, s = lehmer_pi(k);
            if (s >= n) { r = k; }
            else if (s < n) { l = k + 1; }
        }
        cout << r;
    }
}

相关问题