Arcane isPrime method in Java

后端 未结 3 1551
星月不相逢
星月不相逢 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

    This is not a really efficient way to check if a number is prime(it checks every divisor).

    An efficient way is to check for divisors up to sqrt(number). This is if you want to be certain if a number is prime. Otherwise there are probabilistic primality checks which are faster, but not 100% correct.

提交回复
热议问题