Prime Checker

  • + 0 comments

    Since the locked code involves repeat checks of primailty, I factored in some caching so the code doesn't have to repeatedly check values.

    class Prime{
        private static Set<Integer> prime_list = new HashSet<>();
    
        public void checkPrime(int ... nums) {
            for (int num : nums) {
                if (prime_list.contains(num)) {
                    System.out.print(num + " ");
                } else if (isPrime(num)) {
                    prime_list.add(num);
                    System.out.print(num + " ");
                }
            }
            System.out.println();
        }
    
        private static boolean isPrime(int n) {
            if (n < 2) return false;
            else if (n < 4) return true;
            else if (n % 2 == 0) return false;
            
            int sqrt = (int) Math.sqrt(n);
            for (int i = 3; i <= sqrt; i += 2) {
                if (n % i == 0) return false;
            }
            return true;
        }
    }