Which is the fastest algorithm to find prime numbers?

后端 未结 14 1387
情深已故
情深已故 2020-11-22 06:49

Which is the fastest algorithm to find out prime numbers using C++? I have used sieve\'s algorithm but I still want it to be faster!

相关标签:
14条回答
  • 2020-11-22 06:53

    I know it's somewhat later, but this could be useful to people arriving here from searches. Anyway, here's some JavaScript that relies on the fact that only prime factors need to be tested, so the earlier primes generated by the code are re-used as test factors for later ones. Of course, all even and mod 5 values are filtered out first. The result will be in the array P, and this code can crunch 10 million primes in under 1.5 seconds on an i7 PC (or 100 million in about 20). Rewritten in C it should be very fast.

    var P = [1, 2], j, k, l = 3
    
    for (k = 3 ; k < 10000000 ; k += 2)
    {
      loop: if (++l < 5)
      {
        for (j = 2 ; P[j] <= Math.sqrt(k) ; ++j)
          if (k % P[j] == 0) break loop
    
        P[P.length] = k
      }
      else l = 0
    }
    
    0 讨论(0)
  • 2020-11-22 06:55

    I will let you decide if it's the fastest or not.

    using System;
    namespace PrimeNumbers
    {
    
    public static class Program
    {
        static int primesCount = 0;
    
    
        public static void Main()
        {
            DateTime startingTime = DateTime.Now;
    
            RangePrime(1,1000000);   
    
            DateTime endingTime = DateTime.Now;
    
            TimeSpan span = endingTime - startingTime;
    
            Console.WriteLine("span = {0}", span.TotalSeconds);
    
        }
    
    
        public static void RangePrime(int start, int end)
        {
            for (int i = start; i != end+1; i++)
            {
                bool isPrime = IsPrime(i);
                if(isPrime)
                {
                    primesCount++;
                    Console.WriteLine("number = {0}", i);
                }
            }
            Console.WriteLine("primes count = {0}",primesCount);
        }
    
    
    
        public static bool IsPrime(int ToCheck)
        {
    
            if (ToCheck == 2) return true;
            if (ToCheck < 2) return false;
    
    
            if (IsOdd(ToCheck))
            {
                for (int i = 3; i <= (ToCheck / 3); i += 2)
                {
                    if (ToCheck % i == 0) return false;
                }
                return true;
            }
            else return false; // even numbers(excluding 2) are composite
        }
    
        public static bool IsOdd(int ToCheck)
        {
            return ((ToCheck % 2 != 0) ? true : false);
        }
    }
    }
    

    It takes approximately 82 seconds to find and print prime numbers within a range of 1 to 1,000,000, on my Core 2 Duo laptop with a 2.40 GHz processor. And it found 78,498 prime numbers.

    0 讨论(0)
  • 2020-11-22 06:58

    I always use this method for calculating primes numbers following with the sieve algorithm.

    void primelist()
     {
       for(int i = 4; i < pr; i += 2) mark[ i ] = false;
       for(int i = 3; i < pr; i += 2) mark[ i ] = true; mark[ 2 ] = true;
       for(int i = 3, sq = sqrt( pr ); i < sq; i += 2)
           if(mark[ i ])
              for(int j = i << 1; j < pr; j += i) mark[ j ] = false;
      prime[ 0 ] = 2; ind = 1;
      for(int i = 3; i < pr; i += 2)
        if(mark[ i ]) ind++; printf("%d\n", ind);
     }
    
    0 讨论(0)
  • 2020-11-22 07:00
    #include<iostream>
    using namespace std;
    
    void main()
    {
        int num,i,j,prime;
        cout<<"Enter the upper limit :";
        cin>>num;
    
        cout<<"Prime numbers till "<<num<<" are :2, ";
    
        for(i=3;i<=num;i++)
        {
            prime=1;
            for(j=2;j<i;j++)
            {
                if(i%j==0)
                {
                    prime=0;
                    break;
                }
            }
    
            if(prime==1)
                cout<<i<<", ";
    
        }
    }
    
    0 讨论(0)
  • 2020-11-22 07:01

    There is a 100% mathematical test that will check if a number P is prime or composite, called AKS Primality Test.

    The concept is simple: given a number P, if all the coefficients of (x-1)^P - (x^P-1) are divisible by P, then P is a prime number, otherwise it is a composite number.

    For instance, given P = 3, would give the polynomial:

       (x-1)^3 - (x^3 - 1)
     = x^3 + 3x^2 - 3x - 1 - (x^3 - 1)
     = 3x^2 - 3x
    

    And the coefficients are both divisible by 3, therefore the number is prime.

    And example where P = 4, which is NOT a prime would yield:

       (x-1)^4 - (x^4-1)
     = x^4 - 4x^3 + 6x^2 - 4x + 1 - (x^4 - 1)
     = -4x^3 + 6x^2 - 4x
    

    And here we can see that the coefficients 6 is not divisible by 4, therefore it is NOT prime.

    The polynomial (x-1)^P will P+1 terms and can be found using combination. So, this test will run in O(n) runtime, so I don't know how useful this would be since you can simply iterate over i from 0 to p and test for the remainder.

    0 讨论(0)
  • 2020-11-22 07:03

    Is your problem to decide whether a particular number is prime? Then you need a primality test (easy). Or do you need all primes up to a given number? In that case prime sieves are good (easy, but require memory). Or do you need the prime factors of a number? This would require factorization (difficult for large numbers if you really want the most efficient methods). How large are the numbers you are looking at? 16 bits? 32 bits? bigger?

    One clever and efficient way is to pre-compute tables of primes and keep them in a file using a bit-level encoding. The file is considered one long bit vector whereas bit n represents integer n. If n is prime, its bit is set to one and to zero otherwise. Lookup is very fast (you compute the byte offset and a bit mask) and does not require loading the file in memory.

    0 讨论(0)
提交回复
热议问题