Question
Print Twin prime numbers in given range
(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 TwinPrimeInGivenRange
{
public static boolean isPrime(int num)
{
int i=0;
if(num>1)
{
for(i=2;i< num;i++)
{
if(num%i==0)
{
return false;
}
}
return true;
}
else
{
return false;
}
}
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);
isSecondNumberPrime=isPrime(secondNumber);
if(isFirstNumberPrime==true)
{
if(isSecondNumberPrime==true)
{
System.out.println("("+firstNumber+","+secondNumber+")");
}
}
}
}
}
Python
def isPrime(number):
if(number>1):
for i in range(2,number):
if(number%i==0):
return False
return True
else:
return False
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,")")