Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prime number in java 8

I was trying to write a simple prime number program in Java 8. Below is the program. I wanted to reduce the code in isPrime() as well. Is there something that filters the elements from 2 to n/2, and then apply filter for n%i == 0 which would make isPrime irrelevant?

import static java.util.stream.Collectors.toList;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

public class Stream1 {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 20);
        // Prime number 
        System.out.println(numbers.stream()
                             .filter(Stream1::isPrime)
                             .collect(toList()));
    }

    public static boolean isPrime(int number) {
        for (int i = 2; i <= number / 2; i++) {
            if (number % i == 0) {
                return false;
            }
        }
        return true;
    }
}
like image 295
user3310115 Avatar asked Jun 05 '17 10:06

user3310115


People also ask

How do you define a prime number in Java?

Prime number in Java: Prime number is a number that is greater than 1 and divided by 1 or itself only. In other words, prime numbers can't be divided by other numbers than itself or 1. For example 2, 3, 5, 7, 11, 13, 17.... are the prime numbers.

How do you check if a number is prime in Java?

We can use the isPrime() function, which takes the number as input and returns true if the number is prime and false if it is not.

What is IntStream in Java?

An IntStream interface extends the BaseStream interface in Java 8. It is a sequence of primitive int-value elements and a specialized stream for manipulating int values. We can also use the IntStream interface to iterate the elements of a collection in lambda expressions and method references.


1 Answers

IntStream can be used to generate integer stream

public static boolean isPrime(int number) {
    return !IntStream.rangeClosed(2, number/2).anyMatch(i -> number%i == 0); 
}

or

public static boolean isPrime(int number) {
    return IntStream.rangeClosed(2, number/2).noneMatch(i -> number%i == 0);
}
like image 82
Shashwat Kumar Avatar answered Sep 20 '22 18:09

Shashwat Kumar