Question

I want to print all the prime numbers between two numbers. This is my code:

package sphere;

import java.math.BigInteger;
import java.io.*;

class PrimeTest2 {
    public static void main(String args[]) throws java.lang.Exception {
        BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
        String s = r.readLine();
        String [] splitted = s.split(" ");
        BigInteger lower = new BigInteger(splitted[0]);
        BigInteger upper = new BigInteger(splitted[1]);
        int lowerAsInt = Integer.parseInt(splitted[0]);
        int upperAsInt = Integer.parseInt(splitted[1]);
        BigInteger intermediate = lower;

        for (int i=lowerAsInt; i<upperAsInt; i++) {    
            intermediate = intermediate.nextProbablePrime();
            System.out.println(intermediate);
        }
    }
}

When it's run with 1 10 the output is:

2
3
5
7
11
13
17
19
23

Why doesn't it stop at 7?

Was it helpful?

Solution

Because your program says run times (1 to 9) not stop below 10. Instead of your loop you probably want:

BigIntegerupper = BigInteger.valueOf(upperAsInt);
while (intermediate.compareTo(upper) <= 0) {
  System.out.println(intermediate);
  intermediate = intermediate.nextProbablePrime();
}

See the difference? Yours starts at 1 and stops at 9 (less than 10), printing a number on each iteration. The above stops when the number is greater than the upper bound.

OTHER TIPS

You have it set to run where (i<10), not to stop when the value of a prime is greater than 10

You are incrementing i by one each time, so it's going to run from i=1 till i=10 (9 times). if you want it to stop earlier set i = intermediate.

You are counting i from lowerASInt to upperAsInt. You are counting i from 1 to 10. The statement i++ increments i with 1 (one).

So your loop reads: while i is less than 10, print a prime and increment i with 1.

So you will get the first 9 results.

This works if you use JDK8

 BigInteger lower=BigInteger.valueOf(1);
        BigInteger high=BigInteger.valueOf(100);
        Stream.iterate(lower, BigInteger::nextProbablePrime).limit(high.longValueExact())
                .filter(p -> p.compareTo(high) <= 0).forEach(System.out::println);

Please don't use parallel() for the above stream , as it will slow down performance . As a rule of thumb please don't parallelize stream if you have Stream.iterate() or Stream.limit() in your code . A simple benchmark in my vm shows the parallel version is 4 times slower than the iterative one

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top