ADVERTISEMENT
ADVERTISEMENT

Java program for Prime Number | Check whether Number is Prime or Not

Check Prime Number Example in Java - This program will read an integer number and check whether given number is Prime or Not, in this program we will divide number from 2 to number/2, if number divide by any number then number will not be prime number.

Check Prime Number using Java Program

//Java program for Prime Number
 
import java.util.*;
 
public class Prime
{
    public static void main(String args[]){
        int num,loop;
        boolean flag=false;
         
        Scanner bf=new Scanner(System.in);
         
        //input an integer number
        System.out.print("Enter any integer number: ");
        num= bf.nextInt();
         
        //check prime
        for(loop=2; loop<=(num/2); loop++)
        {
            if(num%loop==0)
            {
                flag=true;
                break;
            }
        }
         
        if(flag==false)
            System.out.println(num + " is a prime number.");
        else
            System.out.println(num + " is not a prime number.");
    }
}

Output

    
    [email protected]:~$ javac Prime.java 
    [email protected]:~$ java Prime
    Enter any integer number: 79
    79 is a prime number.


Using function/Method

//Java program for Prime Number
 
import java.util.*;
 
public class Prime
{
    //function to check number is prime or not
    public static boolean isPrime(int num)
    {
        //check prime
        for(int loop=2; loop<=(num/2); loop++)
        {
            if(num%loop==0)
                return false;
        }
         
        return true;
    }
     
    public static void main(String args[]){
        int num,loop;
        boolean flag=false;
         
        Scanner bf=new Scanner(System.in);
         
        //input an integer number
        System.out.print("Enter any integer number: ");
        num= bf.nextInt();
                 
        if(isPrime(num))
            System.out.println(num + " is a prime number.");
        else
            System.out.println(num + " is not a prime number.");
    }
}

Core Java Example Programs »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.