package com.dev.test; import java.util.Scanner; public class PrimeNumber { public static void main(String[] args){ Scanner in = new Scanner(System.in); System.out.print("Enter number : "); while (in.hasNext()){ int num = in.nextInt(); if (isPrime(num)) { System.out.println(num + " is prime number"); } else { System.out.println(num + " is not a prime number"); } System.out.print("Enter number : "); } } public static boolean isPrime(int num) { //check if n is 2 if (num == 2){ return true; } //check if n is a multiple of 2 if (num % 2 == 0){ return false; } //if not, then just check the odds for (int i = 3; i * i <= num; i += 2) { if (num % i == 0) return false; } return true; } }
Wednesday, 20 June 2012
Java program to check the given number is prime or not.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment