Which is the fastest algorithm to find prime numbers?

后端 未结 14 1686
情深已故
情深已故 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条回答
  •  猫巷女王i
    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.

提交回复
热议问题