Java Program to Check whether a Number is Prime or Not using Recursion

This is a Java Program to Find if a Number is Prime or Not using Recursion. A number is said to be a prime number if it is divisible only by itself and unity.

Enter an integer as an input. Now we create a new method named prime which uses if conditons to give the desired result.

Here is the source code of the Java Program to Find if a Number is Prime or Not using Recursion. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

  1.  
  2. import java.util.Scanner;
  3. public class Prime 
  4. {
  5.     public static void main(String[] args) 
  6.     {
  7.         int n, x;
  8.         Scanner s = new Scanner(System.in);
  9.         System.out.print("Enter any number:");
  10.         n = s.nextInt();
  11.         Prime obj = new Prime();
  12.         x = obj.prime(n, 2);
  13.         if(x == 1)
  14.         {
  15.             System.out.println(n+" is prime number");
  16.         }
  17.         else
  18.         {
  19.             System.out.println(n+" is not prime number");
  20.         }
  21.     }
  22.     int prime(int y,int i)
  23.     {
  24.          if(i < y)
  25.         {
  26.             if(y % i != 0) 
  27.             {
  28.                 return(prime(y, ++i));
  29.             } 
  30.             else
  31.             {
  32.                 return 0; 
  33.             }
  34.         }
  35.         return 1;
  36.     }
  37. }

Output:

$ javac Prime .java
$ java Prime
 
Enter any number:17
17 is prime number

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

advertisement
advertisement

Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.