Make sure that the main

My initial function to determine if a number was prime:

bool is_prime(int x) {
    for (int y = 2; y < x; ++y) {
        if (x % y == 0) {
            return false;
        }
    }
    return true;
}

This was done with difficulty O(x), as you may have had to go to x.

I learned about some optimizations and need to check my big-oh. Here is an improved program:

bool is_prime(int x)
{   
    if (x % 2  == 0 && x > 2) {
        return false;
    }
    for (int y = 3; y*y <= x; y += 2) {
        if (x % y == 0) {
            return false;
        }
    }
    return true;
}

Is the fact that I'm moving on now sqrt(), change it to O(sqrt(x))?

+6
source share
2 answers

, n s. O (sqrt (x)). O (N) , N, . , , .

+7

,

(SQRT ())

. :

bool isPrime(int n)
{
    // Boundary cases
    if (n <= 1)  return false;
    if (n <= 3)  return true;

    // This is checked so that we can skip 
    // middle five numbers in below loop
    if (n%2 == 0 || n%3 == 0) return false;

    for (int i=5; i*i<=n; i=i+6)
        if (n%i == 0 || n%(i+2) == 0)
           return false;

    return true;
}
+1

All Articles