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

后端 未结 3 2004
[愿得一人]
[愿得一人] 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:51

    Problem one, you should be using noneMatch (not anyMatch). Problem two, your range is off. Use rangeClosed (or add one to your end) which should be the square root of n (not just n) - and you started with 2 as an initial value in your first test. Also, you might as well make the method static. Like,

    static boolean isPrimeStream(int n) {
        return IntStream.rangeClosed(2, (int) Math.sqrt(n)) 
                .noneMatch(i -> n % i == 0);
    }
    

    Also, we can improve your first example by handling 2 as a special case. That allows you to begin with three and increment by two skipping all even values.

    static boolean isPrime(int n) {
        if (n == 2) {
            return true;
        } else if (n == 1 || n % 2 == 0) {
            return false;
        }
        for (int i = 3; i * i <= n; i += 2) {
            if (n % i == 0) {
                return false;
            }
        }
        return true;
    }
    

提交回复
热议问题