views:

613

answers:

4

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?

+4  A: 

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.

cletus
This actually prints till 11, but yeah it's the right reasoning.
omgzor
A: 

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

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

so you will get the first 9 results.

JesperGJensen
+1  A: 

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

Queue29
A: 

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.

Hardwareguy