How to Check Prime Number in Java


In this example we will show three methods to determine a prime number in Java.

Source Code

1) Junior

package com.beginner.examples;

public class PrimeExample1 {

    public static void main(String[] args) {

    	boolean flag = true;
    	int num = 5;
    	for(int i=2;i<num;i++) 
    	{
	    	if(num%i==0)
	    	{
	    		flag=false;
	    	}
    	}
    	String str = flag ? " is ":" is not ";
    	System.out.println(num+str+"a prime number.");
    }
}

Output:

5 is a prime number.

2) Middle

package com.beginner.examples;

public class PrimeExample2 {

    public static void main(String[] args) {

    	boolean flag = true;
    	int num = 5;
    	if(num < 2) flag=false;
    	if(num == 2) flag=true;
    	if(num%2==0) flag=false;
    	for(int i = 3; i < num; i += 2)
    	{
    		if(num%i == 0)
			{
    			flag=false;
			}
    	}
    	String str = flag ? " is ":" is not ";
    	System.out.println(num+str+"a prime number.");
    }
}

Output:

5 is a prime number.

3) Advanced

package com.beginner.examples;

public class PrimeExample3 {

    public static void main(String[] args) {

    	boolean flag = true;
    	int num = 5;
    	if(num < 2) flag=false;
    	if(num == 2) flag=true;
    	if(num%2==0) flag=false;
    	for(int i = 3; i*i < num; i += 2)
    	{
    		if(num%i == 0)
			{
    			flag=false;
			}
    	}
    	String str = flag ? " is ":" is not ";
    	System.out.println(num+str+"a prime number.");
    }
}

Output:

5 is a prime number.
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments