top of page

2 Methods to find Prime Number in Java

Prime numbers are the numbers that are divided by 1 or the number itself and cannot be divided by any other number without leaving the remainder.


For example, 17 is a prime number. It is only divided by 1 and cannot be divided by any other number with the remainder of 0.


Here we have 2 methods to check whether a given number is prime or not:

  1. Using For Loop

  2. Using Recursion


Method 1: Using For Loop

import java.util.Scanner;
public class Main 
{  
   public static void main(String[] args) 
   {  
       //Take input from the user
       //Create instance of the Scanner class
       Scanner sc = new Scanner(System.in);  
       System.out.println("Enter a number : ");  
       int num = sc.nextInt();  
       int flag=0; 
       int i, temp=num/2;      
       if(num==0||num==1)
       {  
          System.out.println(num+" is not prime number");      
       }
       else
       {  
         for(i=2;i<=temp;i++)
         {      
           if(num%i==0)
           {      
               System.out.println(num+" is not a prime number");      
               flag=1;      
               break;      
           }      
         }      
         if(flag==0)  
         { 
             System.out.println(num+" is a prime number");  
         }  
        }//end of else  
   }   
} 

Output:



Method 2: Using Recursion

import java.util.Scanner;
public class Main 
{  
    static int i=2;
   public static void main(String[] args) 
   {  
       //Take input from the user
       //Create instance of the Scanner class
       Scanner sc = new Scanner(System.in);  
       System.out.println("Enter the number: ");  
       int num = sc.nextInt();  
      
       if (checkPrime(num)) 
        {  
               System.out.print(num+" is a prime number ");  
        }
        else
        {
            System.out.println(num+" is not a prime number "); 
        }
         
   }  
    static boolean checkPrime(int num)
    {
       // Corner cases
       if (num == 0 || num == 1) 
       {
          return false;
       }
       // Checking Prime
       if (num == i)
           return true;
        // Base cases
       if (num % i == 0) 
       {
          return false; 
             
       }
       i++;
       return checkPrime(num);
    }    
} 


Output:



The Tech Platform

0 comments

Comments


bottom of page