Reputation: 21
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.
Upvotes: 0
Views: 6631
Reputation: 2283
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
Consider that:
i % j == 0
), by putting a break;
statement inside the if condition;i >= 3
you can increase it by 2: i += 2
;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.Upvotes: 1
Reputation: 1
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
System.out.println("enter n1:");
int n1=sc.nextInt();
System.out.println("enter n2:");
int n2=sc.nextInt();
int i;
int j;
int flag=0;
for(i=n1;i<=n2;i++)
{
for(j=2;j<i ;j++)
{
if(i % j==0)
{
flag++;
break;
}
}
if(flag==0)
{
System.out.println("i= "+i);
}
flag=0;
}
}
Upvotes: -1
Reputation: 2282
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.
Upvotes: 0