Determining if a number is prime

后端 未结 20 1290
悲哀的现实
悲哀的现实 2020-11-30 03:05

I have perused a lot of code on this topic, but most of them produce the numbers that are prime all the way up to the input number. However, I need code which only checks w

相关标签:
20条回答
  • 2020-11-30 03:34

    If you know the range of the inputs (which you do since your function takes an int), you can precompute a table of primes less than or equal to the square root of the max input (2^31-1 in this case), and then test for divisibility by each prime in the table less than or equal to the square root of the number given.

    0 讨论(0)
  • 2020-11-30 03:34

    This is a quick efficient one:

    bool isPrimeNumber(int n) {
        int divider = 2;
        while (n % divider != 0) {
            divider++;
        }
        if (n == divider) {
            return true;
        }
        else {
            return false;
        }
    }
    

    It will start finding a divisible number of n, starting by 2. As soon as it finds one, if that number is equal to n then it's prime, otherwise it's not.

    0 讨论(0)
提交回复
热议问题