JAVA PROGRAM TO PRINT THE PRIME NUMBERS FROM 1 TO N.

 

 

 

 

 

 

A  prime  number  is  a  whole  number greater  than  1  which  is  only  divisible  by  1  &  the  number  itself i.e. A  prime  number  can’t  be  divided  by  other  numbers  except  1  &  the  number   itself.

 

e.g. 2,3,5,7,11,13,17,19 …..etc.

 

 

 

Approach :

According  to  definition, number ‘n’  is  prime  number  if  it  is  not  divisible  by  any  number  other  than  1  and  n . You  can  also  say, A  prime  number  is  a  number  which is  not  divisible  by  any  number  fron  2  to  n-1. 

 

 

 

 

 

Java  Program

 

 

class    PrimenumbersPrint{

    //function  to  check  if  the  number  is  prime  number  or  not

     static   boolean    isPrime(int n ){

      //As  0  and  1  are  not  prime  numbers  ,so  return  false.

 

  if (n==1||n==0){

   return   false;

       }

 

//Run  a  for loop  from   2  to  n-1

 

      for(int   i=2;i<=(n-1);i++){

 

          if(n%i==0){

             return  false;

       }

    }

 

// Otherwise  n  is   a  prime  number, so  return  true.

 

   return   true;

   }

 

  public  static   void  main(String  args[] ) {

Scanner  sc=new   Scanner(System.in);

System.out.println(“Enter  the  value of  n  to  which  you  want  to  print  the  prime    numbers”);

int   N=sc.nextInt();

//Check  for  every  number  from  1  to  N

 

for(int  i=1;i<=N;i++){

        //check  if  the  current  number  i  is  prime  or  not

 

       if(isPrime(i)){

    System.out.println(i+ ” “);

}

}

 

}

}

 

 

 

 

Leave a Comment

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