java

How to Check Prime Number in Java

Prime number is a number only divisible by 1 or by itself. For example, 3 is only divisible by 3 or by itself. Thus 2, 3, 5, 7, 11, 13, 17…. are prime numbers.

Note: 0 and 1 are not prime numbers. 2 is the only prime and even number.
 

Program to Check Prime Number in Java
public class nbrPremier {
 
 public static void main(String[] args) {
  int remainder;
  boolean flag = true;
  int nbr = 17;
        
  for(int i=2; i <= nbr/2; i++)
  {
     //number is divisible by itself
     remainder = nbr%i;
            
     //if the remainder is 0, then stop the loop. Otherwise continue the loop
     if(remainder == 0)
     {
        flag = false;
        break;
     }
  }
  //if the flag is true, then the number is prime, otherwise not prime
  if(flag)
     System.out.println(nbr + " is a prime number");
  else
     System.out.println(nbr + " is not a prime number");
  }
}

Output:

17 is a prime number
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *