Find all prime numbers within one billion and

Method One: dynamic programming

Details are know almost - find all the prime numbers within a billion and, how to do it the fastest? .

The following code is just a replica version of Python

Time complexity is about $ O (n ^ \ frac {3} {4}) $, but in my computer using the spicy chicken 4s

#include<bits/stdc++.h>
using namespace std;

typedef long long ll;
const int maxn = 2e5+10;
int V[maxn];
map<int, ll>S;

ll Sum(ll n)
{
    int m = (int)sqrt(n);
    int t = n / m;
    for(int i = 1;i <= m;i++)  V[i-1] = n / i;

    int cnt = 1;
    for(int i = t + m - 2;i >= m;i--)  V[i] = cnt++;


    for(int i = 0;i <= t+m-2;i++)  S[V[i]] = 1LL * V[i] * (V[i]+1) / 2 - 1;

    for(int p = 2;p <= m;p++)
    {
        if(S[p] > S[p-1])
        {
            ll sp = S[p-1];
            ll p2 = p *  p;
            for(int i = 0;i <= t+m-2;i++)
            {
                ll v = V[i];
                if(v < p2)  break;
                S[v] -= p*(S[v/p] - sp);
            }
        }
    }

    return S[n];
}

int main()
{
    printf("%lld\n", Sum(1000000000));
}

Method two: Eppendorf sieve

The idea is very simple, screening out all the prime numbers and then added.

Time complexity is $ O (nloglogn) $, when used on my computer 23s.

#include<bits/stdc++.h>
using namespace std;

typedef long long ll;
const int maxn = 1e9 + 10;
bool vis[maxn];

ll sieve(int n)
{
    ll ret = 0;
    int m = (int)sqrt(n + 0.5);
    for (int i = 2; i <= m; i++) if(!vis[i])
    {
        for (int j = i * i; j <= n; j += i)  vis[j] = true;
        ret += i;
    }
    for(int i = m+1;i <= n;i++)  if(!vis[i])
        ret += i;
    return ret;
}

int main()
{
    printf("%lld\n", sieve(1000000000));
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/lfri/p/11479453.html