Print prime numbers up to N and Check N is prime or not using Java Programming Language


 Print prime numbers up to N and Check N is prime or not using Java Programming Language.

 

Answer )

Only the number divided by itself and divided by  1 is called as Prime Number.

Below code is for check prime for number and also print prime numbers for up to that range(N).

Below code is only on Java language.

If it is helpful for you , then comment below .

If you want below code in python , Click Here

Code:

import java.util.*;
 
public class Main
{
     static boolean checkPrime(int n){
        if(n==1 || n ==0 || n<0){
            return false;
        }
        for(int i=2;i<n;i++)
        {
            if(n%i==0){
                return false;
            }
        }
        return true;
    }
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter Number : ");
        int n = sc.nextInt();
        
       
       if(checkPrime(n)){
           System.out.println(n+" is Prime Number");
       }
       else{
           System.out.println(n+" is Not Prime Number");
       }
       
       System.out.print("\nPrime numbers up to "+n+" are : ");
       for(int j =2 ;j<n+1;j++){
           if(checkPrime(j)){
               System.out.print(j+" ");
           }
       }
       
    }
}


Picture View:

 


Output Picture View:

Comments

Post a Comment

Popular posts from this blog

javascript arrow function