How can I improve this code for Project Euler 7?

后端 未结 4 657
悲哀的现实
悲哀的现实 2021-01-27 02:29

By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.

What is the 10 001st prime number?

My solution:



        
4条回答
  •  别那么骄傲
    2021-01-27 03:14

    I would comment, but I just joined.

    You don't have to check every number between 1 and a numbers square root for potential divisors, you just have to check all previous primes (assuming you start at 1 and iterate up), as any other divisor that is not prime will itself be divisible by a prime of a lower value. the higher the number of primes, the more checks against non prime numbers this saves. the example is in C# but that's more to demonstrate the concept.

        //store found primes here, for checking subsequent primes
        private static List Primes;
        private static bool IsPrime(long number)
        {
            //no number will have a larger divisor withou some smaller divisor
            var maxPrime = Math.Sqrt(number);
    
            // takes the list of primes less than the square root and 
            //     checks to see if all of that list is not evenly 
            //     divisible into {number}
            var isPrime = Primes
                .TakeWhile(prime => !(prime > maxPrime))
                .All(prime => number % prime != 0);
            if (isPrime)
                Primes.Add(number);
            return isPrime;
        }
    
        private static long GetNthPrime(int n)
        {
            //reset primes list to prevent persistence
            Primes = new List { 2, 3, 5, 7 };
    
            //prime in starting set
            if (Primes.Count >= n)
            {
                return Primes[n - 1];
            }
    
            //iterate by 6 to avoid all divisiors of 2 and 3 
            //  (also have to check i + 2 for this to work)
            //  similar to incrementing by 2 but skips every third increment 
            //  starting with the second, as that is divisible by 3
            for (long i = 11; i < long.MaxValue; i += 6)
            {
                // only check count if is prime
                if ((IsPrime(i) && Primes.Count >= n) || (IsPrime(i + 2) && Primes.Count >= n))
                {
                    break;
                };
            }
            //return end of list
            return Primes[n - 1];
        }
    

提交回复
热议问题