Is there a simple algorithm that can determine if X is prime?

后端 未结 16 1525
离开以前
离开以前 2020-12-01 00:32

I have been trying to work my way through Project Euler, and have noticed a handful of problems ask for you to determine a prime number as part of it.

  1. I kno

16条回答
  •  不知归路
    2020-12-01 00:58

    Keeping in mind the following facts (from MathsChallenge.net):

    • All primes except 2 are odd.
    • All primes greater than 3 can be written in the form 6k - 1 or 6k + 1.
    • You don't need to check past the square root of n

    Here's the C++ function I use for relatively small n:

    bool isPrime(unsigned long n)
    {
        if (n == 1) return false; // 1 is not prime
        if (n < 4) return true; // 2 and 3 are both prime
        if ((n % 2) == 0) return false; // exclude even numbers
        if (n < 9) return true; //we have already excluded 4, 6, and 8.
        if ((n % 3) == 0) return false; // exclude remaining multiples of 3
    
        unsigned long r = floor( sqrt(n) );
        unsigned long f = 5;
        while (f <= r)
        {
            if ((n % f) == 0)  return false;
            if ((n % (f + 2)) == 0) return false;
            f = f + 6;
        }
        return true; // (in all other cases)
    }
    

    You could probably think of more optimizations of your own.

提交回复
热议问题