Question
Check whether two numbers are twin prime using recursion.
A twin prime is a prime number that is either 2 less or 2 more than another prime number—for example, either member of the twin prime pair (41, 43)
ENTER FIRST NUMBER
41
ENTER SECOND NUMBER
43
41 AND 43 ARE TWIN PRIME NUMBERS
Share code with your friends
Share on whatsapp
Share on facebook
Share on twitter
Share on telegram
Code
Java
Python
Java
import java.util.Scanner;
public class TwinPrimeUsingRecursion
{
public static boolean isPrime(int n,int i)
{
if(n<=1)
{
return false;
}
else if(i==n)
{
return true;
}
else if(n%i==0)
{
return false;
}
else
{
return isPrime(n,(i+1));
}
}
public static void main()
{
int firstNumber=0,secondNumber=0,difference=0;
boolean isFirstNumberPrime=false,isSecondNumberPrime=false;
Scanner sc=new Scanner(System.in);
System.out.println("ENTER FIRST NUMBER:");
firstNumber=sc.nextInt();
System.out.println("ENTER SECOND NUMBER:");
secondNumber=sc.nextInt();
isFirstNumberPrime=isPrime(firstNumber,2);
isSecondNumberPrime=isPrime(secondNumber,2);
difference=Math.abs(firstNumber-secondNumber);
// checking if the difference between two numbers is equal to 2
// else both the number is not twin prime numbers
if(difference==2)
{
if(isFirstNumberPrime==false || isSecondNumberPrime==false)
{
System.out.println(firstNumber+" AND "+secondNumber+" ARE NOT TWIN PRIME NUMBERS");
}
else
{
System.out.println(firstNumber+" AND "+secondNumber+" ARE TWIN PRIME NUMBERS");
}
}
else
{
System.out.println(firstNumber+" AND "+secondNumber+" ARE NOT TWIN PRIME NUMBERS");
}
}
}
Python
def isPrime(n,i=2):
if(n<=1):
return False
elif(i==n):
return True
elif(n%i==0):
return False
else:
return isPrime(n,i+1)
if(__name__=='__main__'):
lowerRange=int(input("Enter the lower value:"))
upperRange = int(input("Enter the upper value:"))
print("Twin Prime numbers between",lowerRange,"and",upperRange,":")
for i in range(lowerRange,upperRange-1):
firstNumber=i
secondNumber=i+2
isFirstNumberPrime=isPrime(firstNumber)
isSecondNumberPrime=isPrime(secondNumber)
if(isFirstNumberPrime==True and isSecondNumberPrime==True):
print("(",firstNumber,",",secondNumber,")")