41.1k views
12 votes
Write a recursive function to determine if a number is prime.

User Asafm
by
3.8k points

1 Answer

5 votes

Answer:

Follows are the code to find the prime number:

import java.util.*;//import package for user input

public class Main//defining a class

{

public static boolean Prime(int x, int j)//defining a method isPrime

{

if (x<= 2) //use if block to check x less than equal to 2

return (x== 2) ? true : false; //use bitwise operator to return value

if (x%j == 0) //use if to check x%j equal to 0

return false;//return false value

if (j*j > x)//defining if that check i square value greater than n

return true; //return true value

return Prime(x, j+1); //callling recursive method

}

public static void main(String[] as)//main method

{

int n; //defining integer variable

Scanner oxc=new Scanner(System.in);//creating Scanner class object

n=oxc.nextInt();//input value

if (Prime(n, 2)) //use if block to call isPrime method

System.out.println("Yes"); //print value

else //else block

System.out.println("No"); //print value

}

}

Output:

5

Yes

Step-by-step explanation:

In this code, a static boolean method "Prime" is declared, that accepts two integer variables in its parameter and defines the if block that checks the prime number condition by the recursive method and returns a value true or false. Inside, the main method an integer variable is declared that uses the Scanner class object for input value and passes into the method and prints its value.

User Emanuella
by
3.3k points