Reputation: 11
package Loops;
import java.util.*;
public class PrimeOrNot
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter any number:");
int n = sc.nextInt();
for (int i = 2;i<=Math.sqrt(n);i++){
if(n%i==0){
System.out.println(n+" is NOT prime");
break;
}
System.out.println(n+ " IS prime");
break;
}
}
}
Upvotes: 0
Views: 40
Reputation: 40062
You need to do a little rearranging. Move the second print statement outside the loop so all values are checked before determining primality. And do a return, not a break so the second print is not executed in case n
is a composite number.
public class PrimeOrNot
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter any number:");
int n = sc.nextInt();
for (int i = 2;i<=Math.sqrt(n);i++){
if(n%i==0){
System.out.println(n+" is NOT prime");
return;
}
}
System.out.println(n+ " IS prime");
}
}
And here is a tip. Check for divisibility by 2 first. Then use the loop to check starting with 3 incrementing by 2 (for all odd divisors). Or combine both tests in the same loop.
for (int i = 2; i<=Math.sqrt(n); i+=(i >= 3) ? 2 : 1 ){...}
Upvotes: 2