Created
April 7, 2022 13:18
-
-
Save aadipoddar/bc9b98987f5365a82fcf8ed54d85f111 to your computer and use it in GitHub Desktop.
Program to check whether the number is prime or not using recursion.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| Write a program to accept a number using int accept() function | |
| and check whether the number is prime or not using recursion. | |
| */ | |
| import java.util.*; | |
| class PrimeCheckRecursive { | |
| int accept() { | |
| Scanner sc = new Scanner(System.in); | |
| System.out.println("Enter a number"); | |
| return sc.nextInt(); | |
| } | |
| boolean isPrime(int n, int k) { | |
| if (n == 1) | |
| return false; | |
| else if (n == k) | |
| return true; | |
| else if (n % k == 0) | |
| return false; | |
| else | |
| return isPrime(n, k + 1); | |
| } | |
| public static void main(String[] args) { | |
| PrimeCheckRecursive pcr = new PrimeCheckRecursive(); | |
| if (pcr.isPrime(pcr.accept(), 2)) | |
| System.out.println("Number is prime"); | |
| else | |
| System.out.println("Number is not prime"); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment