Search code examples
javaloopsnumbersprimes

Prime Numbers In a given range in Java


I am trying to take the input from the user for a range and then finding all the prime numbers in that range. I am using the logic that any nuber that is greater than 2 and less than itself, which is not divisible by any number in this range (2 to less than itself) is a prime number.

public class Main
{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the range : ");
        int n1=sc.nextInt();
        int n2=sc.nextInt();
        int fl=0;
        for(int i=n1;i<n2;i++)
        {
            for(int j=2;j<i;j++)
            { 
                if(i % j == 0)
                {
                    fl=1;
                }
            }
            if(fl == 0)
                System.out.println(i);
        }
        
    }
}

This is the output I am getting: 1 2 3

When the range is 1 to 20 (No more than 3). Please help me out.


Solution

  • 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 19
    Result: 
    2
    3
    5
    7
    11
    13
    17
    19
    

    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.