Fastest way to calculate primes in C#?

后端 未结 8 797
孤独总比滥情好
孤独总比滥情好 2021-02-03 09:56

I actually have an answer to my question but it is not parallelized so I am interested in ways to improve the algorithm. Anyway it might be useful as-is for some people.

相关标签:
8条回答
  • 2021-02-03 10:55

    You might save some time by cross-referencing your bit array with a doubly-linked list, so you can more quickly advance to the next prime.

    Also, in eliminating later composites once you hit a new prime p for the first time - the first composite multiple of p remaining will be p*p, since everything before that has already been eliminated. In fact, you only need to multiply p by all the remaining potential primes that are left after it in the list, stopping as soon as your product is out of range (larger than Until).

    There are also some good probabilistic algorithms out there, such as the Miller-Rabin test. The wikipedia page is a good introduction.

    0 讨论(0)
  • 2021-02-03 10:55
        void PrimeNumber(long number)
        {
            bool IsprimeNumber = true;
            long  value = Convert.ToInt32(Math.Sqrt(number));
            if (number % 2 == 0)
            {
                IsprimeNumber = false;
                MessageBox.Show("No It is not a Prime NUmber");
                return;
            }
            for (long i = 3; i <= value; i=i+2)
            {             
               if (number % i == 0)
                {
    
                    MessageBox.Show("It is divisible by" + i);
                    IsprimeNumber = false;
                    break;
                }
    
            }
            if (IsprimeNumber)
            {
                MessageBox.Show("Yes Prime NUmber");
            }
            else
            {
                MessageBox.Show("No It is not a Prime NUmber");
            }
        }
    
    0 讨论(0)
提交回复
热议问题