Quantcast
Channel: User mikyll98 - Stack Overflow
Viewing all articles
Browse latest Browse all 104

Answer by mikyll98 for Prime Numbers In a given range in Java

$
0
0

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 a break; 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 to j * j <= i (equivalent to j <= sqrt(i)). In fact, there's no need to check divisors greater than the square root of i, as any larger divisor would correspond to a smaller one already tested. For example, if the number to check is 91, we just need to test up until sqrt(91) = 9.539 ~= 9, so 2, 3, 5 and 7. We don't check 13 and the others, because their corresponding divisors (in this case, for 13 is 7, because 7 * 13 = 91) would have been already checked.

Viewing all articles
Browse latest Browse all 104

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>