Home > Back-end >  Prime Numbers In a given range in Java
Prime Numbers In a given range in Java

Time:08-20

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.

CodePudding user response:

You have to reset your flag fl back to 0 at the start of every iteration of the outer loop.
At the moment once you encounter a non-prime (i.e. 4) it will set the value to 1 and then keep it for the remaining numbers.

CodePudding user response:

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
  • Related