Time Complexity: Primality

  • + 5 comments

    Java solution - passes 100% of test cases

    O(n^(1/2)) solution. We also skip even numbers for faster results.

    Alternatively, we could do preprocessing using the Sieve of Erasthenes and save the primes (up to a certain number) in an array or HashSet. Then determing if a number is prime would take O(1) time since it would be a simple lookup.

    public class Solution {
        public static void main(String[] args) {
            Scanner scan = new Scanner(System.in);
            int p = scan.nextInt();
            while (p-- > 0) {
                int n = scan.nextInt();
                System.out.println(isPrime(n) ? "Prime" : "Not prime");
            }
            scan.close();
        }
        
        public static boolean isPrime(int n) {
            if (n < 2) {
                return false;
            } else if (n == 2) {
                return true;
            } else if (n % 2 == 0) {
                return false;
            }
            int sqrt = (int) Math.sqrt(n);
            for (int i = 2; i <= sqrt; i ++) {
                if (n % i == 0) {
                    return false;
                }
            }
            return true;
        }
    }
    

    From my HackerRank Java solutions.