Search code examples
c++c++17primes

what is the Time Complextity of a below function?


#include <iostream>

using namespace std;

bool isPrime(int n){
     if(n == 1 || n == -1)
          return false
     else if (n ==2 || n == 3)
          return true;
     else if((n+1)%6 == 0 || (n-1)%6 == 0)
          return true;
     return false;
}

int main()
{
    int n{0};
    cin >> n;
    cout << isPrime(n) << endl;
    return 0;
}

what is the time complexity of isPrime() function and is it correct solution to check whether the number is prime or not ?


Solution

  • It only does a handful of divisibility checks and has no loops or recursion, thus it is simply O(1) and is not a correct prime number check.

    The third check makes very little sense. Why would a number be prime if it is one away from a multiple of 6? I mean it happens to work for 5 and 7, for 11 and 13, and for 17 and 19, but fails for 25. 25 is one away from 24 but is not prime. It's like calculating π as 22/7 — it's an okay first approximation but it's clearly not the right formula.