Most efficient code for the first 10000 prime numbers?

前端 未结 30 1414
日久生厌
日久生厌 2020-11-29 19:09

I want to print the first 10000 prime numbers. Can anyone give me the most efficient code for this? Clarifications:

  1. It does not matter if your code is ineffici
30条回答
  •  Happy的楠姐
    2020-11-29 19:41

    Adapting and following on from GateKiller, here's the final version that I've used.

        public IEnumerable PrimeNumbers(long number)
        {
            List primes = new List();
            for (int i = 2; primes.Count < number; i++)
            {
                bool divisible = false;
    
                foreach (int num in primes)
                {
                    if (i % num == 0)
                        divisible = true;
    
                    if (num > Math.Sqrt(i))
                        break;
                }
    
                if (divisible == false)
                    primes.Add(i);
            }
            return primes;
        }
    

    It's basically the same, but I've added the "break on Sqrt" suggestion and changed some of the variables around to make it fit better for me. (I was working on Euler and needed the 10001th prime)

提交回复
热议问题