import java.util.*;
public class PrimeNum {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int a = input.nextInt();
int b = input.nextInt();
for(int i = a ; i <= b ; i++ ) {
if ( i == 2 || i == 3 ) System.out.println(i);
for(int j = 2; j <= (i / 2) ; j++ ) {
if ( (i % j) == 0 ) break;
if ( j == (i / 2) ) System.out.println(i);
}
}
}
}
This program is simple, type in 2 int a and b. It will find any Prime Number within a and b.
How can I make this faster ?. I tried the Math.sqrt one but it does not work well in this case 🙁 I do not really know because whenever I use it, it causes a lot of bugs. I would love to see someone use Squareroot in this case.
I agree with the suggestions to use a different approach, but I’ll try to explain why your approach doesn’t work.
I think the problem is in the way you are printing the result:
This works fine for
i / 2but it will fail forMath.sqrt(i)because it is not always a whole number and thenj == Math.sqrt(i)will never be true. Your code will only work wheniis an exact square.It would be better to refactor your code so that your primality test is in a separate method: