Prime Numbers in given range with Java-8

zijotah :

I am writing a program to calculate the number of prime numbers in a given range.

My code is as below:

public class MultiLineInput {
    static int k=0;
    public static void main (String[] args) {

        Scanner s = new Scanner(System.in);
        int numberOfLinesToRead =  2;//  s.nextInt();
        int []  array = new int [numberOfLinesToRead];
            for(int i=0;i<array.length;i++){
                array[i]=s.nextInt();
            }
        List<Integer> list = IntStream.rangeClosed(array[0], array[1]).boxed().collect(Collectors.toList());
        IntStream.rangeClosed(array[0], array[1]).boxed().map(k -> {
           if(BigInteger.valueOf(list.get(k)).isProbablePrime(1)==true){
               k++;
               return true;
           }
              return false;
        });
        System.out.println(k);

    }
}

The input is as follows:

1
20

Output:

0

Expected Output:

8
Eran :

You have two k variables.

One is static which you never change, so it remains 0.

The other, which you increment inside the Stream pipeline is a local variable, so incrementing it has no effects after the pipeline is done.

In addition, your second Stream pipeline has no terminal operation, so it doesn't process the elements of the Stream.

Also, I suggest not to use side effects (i.e. incrementing a static variable) inside the Stream pipeline. Use filter instead of map and count the number of elements in the filtered Stream:

long result = IntStream.range(array[0], array[1])
                       .boxed()
                       .filter(n -> BigInteger.valueOf(n).isProbablePrime(1))
                       .count();

Note that your first Stream pipeline (which produces a List) is not necessary.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=164176&siteId=1