The Java code checks whether a given number is prime or not using a recursive function. Here's how the code works:
The implementation seems correct and efficient, as it uses recursion to check all possible factors of the given number until it finds a factor or reaches the minimum possible factor (1). However, for large inputs, the recursion may cause stack overflow due to excessive function calls. A more optimized version can be implemented by checking the factors of the number only up to its square root.
import java.util.*; public class PrimeNot { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.printf("Enter the Number : "); int num = input.nextInt(); int res = checkPrimeNot(num, num / 2); if (res == 1) { System.out.printf("This is a Prime Number"); } else { System.out.printf("This is a Not Prime Number"); } } public static int checkPrimeNot(int num, int i) { if (i != 1) { if (num % i != 0) { return checkPrimeNot(num, i - 1); } return 0; } return 1; } }
Enter the Number : 71 This is a Prime Number
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions