Java Program to Check if Number is Prime or Not

[2802 views]




In this article, we will write a java program which checks if the number given as input to the Program is Prime Number or Not.

Program to Check if given number is Prime Number or Not using java

Method 1: Simpler to Understand

import java.util.Scanner; public class CheckPrime { public static void main(String args[]) { boolean isPrime=true; Scanner sc= new Scanner(System.in); System.out.println("Enter any number:"); //Take the input from user int num=sc.nextInt(); if(num<=1){ isPrime=false; }else{ for(int i=2;i<num/2+1;i++){ if(num%i==0){ isPrime=false; break; } } //If isPrime is true then the number is prime number else not prime if(isPrime) System.out.println(num + " is a Prime Number"); else System.out.println(num + " is not a Prime Number"); } } }

Method 2: Optimized Code

import java.util.Scanner; public class CheckPrime { public static void main(String args[]) { boolean isPrime=true; Scanner sc= new Scanner(System.in); System.out.println("Enter any number:"); //Take the input from user int num=sc.nextInt(); int sqrt = (int) Math.sqrt(num) + 1; if(num<=1){ isPrime=false; }else{ // here the loop iterates only upto the square root of the Number. // As all remaining iterations are useless. for(int i=2;i<sqrt;i++){ if(num%i==0){ isPrime=false; break; } } //If isPrime is true then the number is prime number else not prime if(isPrime) System.out.println(num + " is a Prime Number"); else System.out.println(num + " is not a Prime Number"); } } }

Output:

$javac CheckPrime.java $java CheckPrime Enter any number: 23 23 is a Prime Number

Similar Posts:

                 



Clear Any Java Interview by Reading our Ebook Once.


Can you clear Java Interview?




Comments

2 comment
  • Heli Villarreal

    Isn't it better to check up to sqrt(num) + 1 ??

  • Shaddy

    Hey Heli Villarreal, Thanks for your Suggestion. The article has been updated as you suggested. As our website is viewed mostly by beginners, so we were focusing more on simplicity and not on optimizing code.










Search Anything:

Sponsored Deals ends in



Interesting Technical Quizzes:

Search Tags