Tag: Recursion
Emirp Number
An emirp number is a number which is prime backwards and forwards. Example : 13 and 31 are both prime numbers. Thus 13 is a emirp number.
import java.util.*;
class Emirp
{
int n, rev,f;
Emirp(int nn)
{
n=nn;
rev=0;
f=2;
}
int isprime(int x)
{
if(n==x)
return 1;
else if (n%x==0 || n==1)
return 0;
else
return isprime(x+1);
}
void isEmirp()
{
int x=n;
while(x!=0)
{
rev=rev*10 + x%10;
x=x/10;
}
int ans1=isprime(f);
n=rev;
f=2;
int ans2=isprime(f);
if(ans1==1 && ans2==1)
System.out.println(n+"is an emirp no");
else
System.out.println(n+"is not an emirp no.");
}
public static void main(String[] args)
{
int a;
Scanner sc= new Scanner(System.in);
System.out.println("Enter the number:");
a=sc.nextInt();
Emirp emp=new Emirp(a);
emp.isEmirp();
}
}
Enter the number:
13
31is an emirp no
Enter the number:
51
15is not an emirp no.
Java program – Factorial using recursion
import java.util.*;
class factRec
{
int factorial(int n) //5 ! =5*4*3*2*1 =120
{
if (n == 0) // 0!=1 so when given number is 0, it returns 1
return 1;
else // finding factorial by n * factorial(n-1)
return(n * factorial(n-1));
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
factRec fr=new factRec(); //creating object fr
System.out.println("Enter the number to find the factorial");
int number=sc.nextInt();//It is the number to calculate factorial
int fact=1;
fact = fr.factorial(number); //method invocation factorial(number)
// calling recursive method
System.out.println("Factorial of "+number+" is: "+fact);
}
}
Output:
Enter the number to find the factorial
5
Factorial of 5 is: 120
Enter the number to find the factorial
8
Factorial of 8 is: 40320
Recursive method
Find the output of the following fragment:
public class st
{
static int strange(int x,int y)
{
if(x>=y)
{
x=x-y;
return strange(x,y);
}
else
return x;
}
}
dry run
1 x=20,y=5 strange(20,5)
2. x=15,y=5 strange (15,5)
3. x=10,y=5 strange (10,5)
4. x=5,y=5 strange(5,5)
5. x=0,y=5 strange(0,5)
returns 0;
Recursive method
A method which calls itself from its body is known as recursive method.
Eg:
public int fact( int n)
{
if(n==1)
return 1;
else
return (n * fact(n-1));
}