Prime Number Program in Java

Configurare noua (How To)

Situatie

Prime number in Java: Prime number is a number that is greater than 1 and divided by 1 or itself only. In other words, prime numbers can’t be divided by other numbers than itself or 1.

Backup

Let’s see the prime number program in java. In this java program, we will take a number variable and check whether the number is prime or not.

  1. public class PrimeExample{
  2.  public static void main(String args[]){
  3.   int i,m=0,flag=0;
  4.   int n=3;//it is the number to be checked  
  5.   m=n/2;
  6.   if(n==0||n==1){
  7.    System.out.println(n+” is not prime number”);
  8.   }else{
  9.    for(i=2;i<=m;i++){
  10.     if(n%i==0){
  11.      System.out.println(n+” is not prime number”);
  12.      flag=1;
  13.      break;
  14.     }
  15.    }
  16.    if(flag==0)  { System.out.println(n+” is prime number”); }
  17.   }//end of else
  18. }
  19. }

Output:

3 is prime number

Solutie

Tip solutie

Permanent

Voteaza

(9 din 16 persoane apreciaza acest articol)

Despre Autor

Leave A Comment?