Prime Number Formula

前端 未结 13 1644
情话喂你
情话喂你 2020-12-06 08:47

I am trying to write a prime number function in C# and I am wondering if the follow code will work. It \"appears\" to work with the first 50 numbers or so. I just want to ma

13条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-06 09:23

    There are some basic rules you can follow to check if a number is prime

    1. Even numbers are out. If x % 2 = 0, then it is not prime
    2. All non-prime numbers have prime factors. Therefore, you only need test a number against primes to see if it factors
    3. The highest possible factor any number has is it's square root. You only need to check if values <= sqrt(number_to_check) are even divisible.

    Using that set of logic, the following formula calculates 1,000,000 Primes Generated in: 134.4164416 secs in C# in a single thread.

        public IEnumerable GetPrimes(int numberPrimes)
        {
          List primes = new List { 1, 2, 3 };
          long startTest = 3;
    
          while (primes.Count() < numberPrimes)
          {
            startTest += 2;
            bool prime = true;
            for (int pos = 2; pos < primes.Count() && primes[pos] <= Math.Sqrt(startTest); pos++)
            {
              if (startTest % primes[pos] == 0)
              {
                prime = false;
              }
            }
            if (prime)
              primes.Add(startTest);
          }
          return primes;
        }
    

    Bear in mind, there is lots of room for optimization in the algorithm. For example, the algorithm could be parallelized. If you have a prime number (let's say 51), you can test all the numbers up to it's square (2601) for primeness in seperate threads as all it's possible prime factors are stored in the list.

提交回复
热议问题