Given below is the code to check if a given number is prime or not.
class prime{
public static void main(String args[]){
int n = 139;
if(isPrime(n)){
System.out.println(n+" is prime.");
}
else{
System.out.println(n+" is not prime");
}
}
//Function to check if a number is prime or not
static boolean isPrime(int n){
int mid = n/2;
if(n == 0 || n == 1){
return false;
}
for(int i = 2; i <= mid; i++){
if(n%i == 0){
return false; //Returns false if the number is divisible by any number
}
}
return true; //Returns true if the number is not divisible by any other number other than 1 and the number itself
}
}
OUTPUT
139 is prime
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Given below is the code to check if a given number is prime or not.
public class PrimeNumberCheck { public static void main(String[] args) { System.out.println(isPrime(19)); // true System.out.println(isPrime(49)); // false } public static boolean isPrime(int n) { if (n == 0 || n == 1) { return false; } if (n == 2) { return true; } for (int i = 2; i <= n / 2; i++) { if (n % i == 0) { return false; } } return true; } }Output.
true
false