4

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))?

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
  • @MattTimmermans Concur with you and AndyG's suggestion. I wrote the function with `x` so it should've been `x` not `n`. –  Aug 12 '17 at 23:16
  • Another optimisation would be to pre-compute the integer square root of `x` (i.e. find an integer `m`, such that `m*m` is between `x-1` and `x` for positive `x`). There are efficient algorithms (complexity O(log(x)) or better) for computing an integer square root, without resorting to floating point. – Peter Aug 13 '17 at 00:36
  • @Peter I had originally don't the floating point conversion, but the math showed that `m*m` would serve its purpose here. –  Aug 13 '17 at 02:16

2 Answers2

7

Yes, but here are no ns. The complexity of your new function is O(sqrt(x)). When you say O(N) and don't specify what N is, it's generally taken to be the size of the input. This is confusing for functions that take a single number argument, so in those cases you should be explicit.

Matt Timmermans
  • 53,709
  • 3
  • 46
  • 87
1

Absolutely, The complexity of your new function is

O(sqrt(x))

But still, there is some room for optimization. Have a look at the code mentioned below:

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;
}
Kashif Faraz Shamsi
  • 513
  • 1
  • 7
  • 21