Sieve of Atkin explanation

前端 未结 5 1421
一个人的身影
一个人的身影 2020-12-13 19:50

I am doing a project at the moment and I need an efficient method for calculating prime numbers. I have used the sieve of Eratosthenes but, I have been searching around and

5条回答
  •  一个人的身影
    2020-12-13 20:19

    // Title : Seive of Atkin ( Prime number Generator) 
    
    #include 
    #include 
    #include 
    
    using namespace std;
    
    int main()
    {
        ios_base::sync_with_stdio(false);
        long long int n;
        cout<<"Enter the value of n : ";
        cin>>n;
        vector is_prime(n+1);
        for(long long int i = 5; i <= n; i++)
        {
            is_prime[i] = false;
        }
        long long int lim = ceil(sqrt(n));
    
        for(long long int x = 1; x <= lim; x++)
        {
            for(long long int y = 1; y <= lim; y++)
            {
                long long int num = (4*x*x+y*y);
                if(num <= n && (num % 12 == 1 || num%12 == 5))
                {
                    is_prime[num] = true;
                }
    
                num = (3*x*x + y*y);
                if(num <= n && (num % 12 == 7))
                {
                    is_prime[num] = true;
                }
    
                if(x > y)
                {
                    num = (3*x*x - y*y);
                    if(num <= n && (num % 12 == 11))
                    {
                        is_prime[num] = true;
                    }
                }
            }
        }
        // Eliminating the composite by seiveing
        for(long long int i = 5; i <= lim; i++)
        {
            if(is_prime[i])
                for(long long int j = i*i; j <= n; j += i)
                {
                    is_prime[j] = false;
                }
        }
        // Here we will start printing of prime number
       if(n > 2)
       {
           cout<<"2\t"<<"3\t";
       }
       for(long long int i = 5; i <= n; i++)
       {
             if(is_prime[i])
             {
                 cout<

提交回复
热议问题