Arcane isPrime method in Java

后端 未结 3 1548
星月不相逢
星月不相逢 2020-12-14 23:12

Consider the following method:

public static boolean isPrime(int n) {
    return ! (new String(new char[n])).matches(\".?|(..+?)\\\\1+\");
}
<
3条回答
  •  误落风尘
    2020-12-15 00:05

    The unary characteristics of primes and why this works has already been covered. So here's a test using conventional approaches and this approach:

    public class Main {
    
        public static void main(String[] args) {
            long time = System.nanoTime();
            for (int i = 2; i < 10000; i++) {
                isPrimeOld(i);
            }
            time = System.nanoTime() - time;
            System.out.println(time + " ns (" + time / 1000000 + " ms)");
            time = System.nanoTime();
            for (int i = 2; i < 10000; i++) {
                isPrimeRegex(i);
            }
            time = System.nanoTime() - time;
            System.out.println(time + " ns (" + time / 1000000 + " ms)");
            System.out.println("Done");
        }
    
        public static boolean isPrimeRegex(int n) {
            return !(new String(new char[n])).matches(".?|(..+?)\\1+");
        }
    
        public static boolean isPrimeOld(int n) {
            if (n == 2)
                return true;
            if (n < 2)
                return false;
            if ((n & 1) == 0)
                return false;
            int limit = (int) Math.round(Math.sqrt(n));
            for (int i = 3; i <= limit; i += 2) {
                if (n % i == 0)
                    return false;
            }
            return true;
        }
    }
    

    This test computes whether or not the number is prime up to 9,999, starting from 2. And here's its output on a relatively powerful server:

    8537795 ns (8 ms)
    30842526146 ns (30842 ms)
    Done
    

    So it is grossly inefficient once the numbers get large enough. (For up to 999, the regex runs in about 400 ms.) For small numbers, it's fast, but it's still faster to generate the primes up to 9,999 the conventional way than it is to even generate primes up to 99 the old way (23 ms).

提交回复
热议问题