Download Our Beta Android App And Help Us Build Awesome Stuff!  Download Now.

Java Program to check if a number is prime

Prime.txt
File size: 884 Bytes

File content type: text/plain

Category: Assignment

Course: B.Tech., ISC Board, and ICSE Board

Semester: 5

/**
 *
 * @program To check if entered number is prime or not
 */

import java.io.*;

class Prime {

    public static void main(String args[]) throws IOException {

        BufferedReader k = new BufferedReader(new InputStreamReader(System.in));

        System.out.println("Enter number");
        int num = Integer.parseInt(k.readLine());

        if(isPrime(num))
            System.out.println(num + " is a prime number");
        else
            System.out.println(num + " is not a prime number");


    }

    static boolean isPrime(int n) {
        //since 2 is the only even prime number
        if(n > 2 && n % 2 == 0)
            return false;
            //check odd numbers that are prime
        for(int i = 3;i < Math.sqrt(n)+1 ; i=i+2){
            if(n%i == 0)
                return false;
        }
        return true;
    }
}

Added by passhojao

Comments