Prime number calculation fun

前端 未结 18 1833
深忆病人
深忆病人 2020-12-05 15:32

We\'re having a bit of fun here at work. It all started with one of the guys setting up a Hackintosh and we were wondering whether it was faster than a Windows Box of (nearl

18条回答
  •  广开言路
    2020-12-05 15:51

    C#

    Enhancement to Aistina's code:

    This makes use of the fact that all primes greater than 3 are of the form 6n + 1 or 6n - 1.

    This was about a 4-5% speed increase over incrementing by 1 for every pass through the loop.

    class Program
    {       
        static void Main(string[] args)
        {
            DateTime start = DateTime.Now;
    
            int count = 2; //once 2 and 3
    
            int i = 5;
            while (count < 150000)
            {
                if (IsPrime(i))
                {
                    count++;
                }
    
                i += 2;
    
                if (IsPrime(i))
                {
                    count++;
                }
    
                i += 4;
            }
    
            DateTime end = DateTime.Now;
    
            Console.WriteLine("Total time taken: " + (end - start).TotalSeconds.ToString() + " seconds");
            Console.ReadLine();
        }
    
        static bool IsPrime(int n)
        {
            //if (n < 4)
            //return true;
            //if (n % 2 == 0)
            //return false;
    
            int s = (int)Math.Sqrt(n);
            for (int i = 2; i <= s; i++)
                if (n % i == 0)
                    return false;
    
            return true;
        }
    }
    

提交回复
热议问题