Using java streams to find if a number is prime or not

后端 未结 3 2017
[愿得一人]
[愿得一人] 2021-01-17 07:15

I am reading Cracking the Coding Interview and it has an example of finding prime number which I ran on JShell

boolean isPrime(int n) {
  for (int i         


        
3条回答
  •  滥情空心
    2021-01-17 07:53

    What is the point of using Java8 streams to get this thing done. To me you are reinventing the wheel. This one liner will be suffice.

    BigInteger.valueOf(n).isProbablePrime(50);
    

    Also notice that there are some problems which can be better solved using streams. But that does not mean stream is the silver bullet to solve all your problems.

    Here's an excerpt from the Documentation about certainty.

    For a large known prime, and for any certainty > 0, is it accurate to say that b.isProbablePrime(certainty) will always return true.

提交回复
热议问题