Advertisements
to check wethere given number is prime or not?
Hi Friend,
Try this:
import java.util.*; class CheckPrimeNumber { static boolean isPrime(int number){ boolean isPrime=false; int i=(int) Math.ceil(Math.sqrt(number)); while (i>1){ if ((number!=i) && (number%i==0)){ isPrime=false; break; } else if (!isPrime) isPrime=true; --i; } return isPrime; } public static void main(String[] args) { Scanner input=new Scanner(System.in); System.out.println("Enter Number:"); int num=input.nextInt(); if(isPrime(num)){ System.out.println("Number is Prime!"); } else{ System.out.println("Number is not prime!"); } } }
Thanks
import java.io.*; public class Primenumber1 { public static void main(String args[]) { InputStreamReader ir = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(ir); int num; try{ int a =Integer.parseInt(br.readLine()); if(a%2!=0 || a==2) { System.out.println(a + "is a prime number"); } else { System.out.println(a + "is not a prime number"); } } catch(Exception e){} } }
This code is better for begginers
import java.io.*;
public class Primenumber1
{
public static void main(String args[]) { InputStreamReader ir = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(ir); int num; try{ int a =Integer.parseInt(br.readLine()); if(a%2!=0 || a==2) { System.out.println(a + "is a prime number"); } else { System.out.println(a + "is not a prime number"); } } catch(Exception e){} }
}