As pointed out by Turamarth, you need to reset the flag at each iteration. I also suggest you to loop until i <= n2
, otherwise you would miss the last number, and add an input check.
public static void main(String args[]){ int n1; int n2; boolean flag; Scanner sc = new Scanner(System.in); System.out.print("Enter the range: "); n1 = sc.nextInt(); n2 = sc.nextInt(); sc.close(); if (n1 < 2) n1 = 2; if (n2 < 2) { System.out.println("No prime numbers in range."); return; } System.out.println("Result: "); for(int i = n1; i <= n2; i++) { flag = false; for(int j = 2; j < i; j++) { if(i % j == 0) { flag = true; } } if(!flag) System.out.println(i); }}
Example with [1, 19]:
Enter the range: 1 19Result: 235711131719
Optimizations
Consider that:
- you could break out from the second loop when you find a divisor (
i % j == 0
), by putting abreak;
statement inside the if condition; - after 2 all prime numbers are odd, therefore when
i >= 3
you can increase it by 2:i += 2
; - as suggested by user85421, instead of testing up to
j < i
, you can just test up toj * j <= i
(equivalent toj <= sqrt(i)
). In fact, there's no need to check divisors greater than the square root ofi
, as any larger divisor would correspond to a smaller one already tested. For example, if the number to check is91
, we just need to test up untilsqrt(91) = 9.539 ~= 9
, so2
,3
,5
and7
. We don't check13
and the others, because their corresponding divisors (in this case, for13
is7
, because7 * 13 = 91
) would have been already checked.