xyz
xyz

Reputation: 11

Following code for prime or not is not working for 2 and 3

  1. The code for prime or not, is not working for 2 and 3. If in the same code instead of printing prime or not right there, we assign a boolean and later use the boolean to print prime or not, it works. I want to know why.
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

Answers (1)

WJS
WJS

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

Related Questions