Prime Number Formula

前端 未结 13 1646
情话喂你
情话喂你 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:35

    Primality testing is the way to go, but in case you want a quick and dirty hack, here's something.

    If it's not working fast enough, you can build a class around it and store the PrimeNumbers collection from call to call, rather than repopulating it for each call.

        public bool IsPrime(int val)
        {
            Collection PrimeNumbers = new Collection();
            int CheckNumber = 5;
            bool divisible = true;
            PrimeNumbers.Add(2);
            PrimeNumbers.Add(3);
    
            // Populating the Prime Number Collection
            while (CheckNumber < val)
            {
                foreach (int i in PrimeNumbers)
                {
                    if (CheckNumber % i == 0)
                    {
                        divisible = false;
                        break;
                    }
                    if (i * i > CheckNumber) { break; }
                }
                if (divisible == true) { PrimeNumbers.Add(CheckNumber); }
                else { divisible = true; }
                CheckNumber += 2;
            }
            foreach (int i in PrimeNumbers)
            {
                if (CheckNumber % i == 0)
                {
                    divisible = false;
                    break;
                }
                if (i * i > CheckNumber) { break; }
            }
            if (divisible == true) { PrimeNumbers.Add(CheckNumber); }
            else { divisible = true; }
    
            // Use the Prime Number Collection to determine if val is prime
            foreach (int i in PrimeNumbers)
            {
                if (val % i == 0) { return false; }
                if (i * i > val) { return true; }
            }
            // Shouldn't ever get here, but needed to build properly.
            return true;
        }
    

提交回复
热议问题