Question
Print Twin Prime numbers in given range using recursion
(Twin Primes are the prime numbers with a difference of 2.)
Example: (3 and 5),(5 and 7),(11 and 13) etc
Enter the lower value:-10
Enter the upper value:90
Twin Prime numbers between -10 and 90 :
( 3 , 5 )
( 5 , 7 )
( 11 , 13 )
( 17 , 19 )
( 29 , 31 )
( 41 , 43 )
( 59 , 61 )
( 71 , 73 )
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 TwinPrimeInGivenRangeUsingRecursion
{
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 lowerRange=0,upperRange=0,difference=0,i=0,firstNumber=0,secondNumber=0;
boolean isFirstNumberPrime=false,isSecondNumberPrime=false;
Scanner sc=new Scanner(System.in);
System.out.println("ENTER LOWER VALUE:");
lowerRange=sc.nextInt();
System.out.println("ENTER UPPER VALUE:");
upperRange=sc.nextInt();
System.out.println("Twin Prime numbers between "+lowerRange+" and "+upperRange+":");
for(i=lowerRange;i<=upperRange-2;i++)
{
firstNumber=i;
secondNumber=i+2;
isFirstNumberPrime=isPrime(firstNumber,2);
isSecondNumberPrime=isPrime(secondNumber,2);
if(isFirstNumberPrime==true)
{
if(isSecondNumberPrime==true)
{
System.out.println("("+firstNumber+","+secondNumber+")");
}
}
}
}
}
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,")")