How to create the most compact mapping n → isprime(n) up to a limit N?

后端 未结 30 2710
遇见更好的自我
遇见更好的自我 2020-11-22 02:11

Naturally, for bool isprime(number) there would be a data structure I could query.
I define the best algorithm, to be the algorithm that pr

30条回答
  •  梦如初夏
    2020-11-22 02:54

    With help of Java-8 streams and lambdas, it can be implemented like this in just few lines:

    public static boolean isPrime(int candidate){
            int candidateRoot = (int) Math.sqrt( (double) candidate);
            return IntStream.range(2,candidateRoot)
                    .boxed().noneMatch(x -> candidate % x == 0);
        }
    

    Performance should be close to O(sqrt(N)). Maybe someone find it useful.

提交回复
热议问题