I am unable to get all the prime numbers printed .can someone help me with this .I get all the values except 2 and 3 . It starts with 5 .
public static void primesinRange(int n) {
int flag=1;
int i, j=2;
for(i=2;i<=n;i++) {
if(n==1 || n==0) {
continue;
}
if(n==2) {
flag=1;
continue;
}
flag=1;
for(j=2;j<=Math.sqrt(n);j++) {
if((i%j)==0) {
flag=0;
break;
}
}
if(flag==1) {
System.out.print(i+ " ");
}
}
}
You need to change the condition of your inner for-loop from
j<=Math.sqrt(n)
to
j<=Math.sqrt(i)
Otherwise for sufficiently large values of n
this range will include the small i
values.