×

Java Programs

Java Practice

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

    
    me@linux:~$ javac Prime.java 
    me@linux:~$ 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 »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.