Check if prime big-o

Viewed 1522

My original function to determine if a number was prime was:

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

This ran with a complexity of O(x) as you may have had to go to x.

I've learned of some optimizations and need a check on my big-o. Here is the 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;
}

Does the fact that I am now going up to the sqrt() change this to O(sqrt(x))?

2 Answers
Related