Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prime Numbers in given range with Java-8

Tags:

java

java-8

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
like image 312
zijotah Avatar asked Apr 30 '26 00:04

zijotah


1 Answers

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.

like image 94
Eran Avatar answered May 02 '26 13:05

Eran