Question
Check whether Two numbers are twin prime numbers or not
(Twin Primes are the prime numbers with a difference of 2.)
Example: (3 and 5),(5 and 7),(11 and 13) etc
Enter the First number:5
Enter the Second number:7
5 and 7 are Twin prime number
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 TwinPrime
{
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 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);
isSecondNumberPrime=isPrime(secondNumber);
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(number):
if(number>1):
for i in range(2,number):
if(number%i==0):
return False
return True
else:
return False
if(__name__=='__main__'):
firstNumber=int(input("Enter the First number:"))
secondNumber=int(input("Enter the Second number:"))
isFirstNumberPrime=isPrime(firstNumber)
isSecondNumberPrime=isPrime(secondNumber)
differenceBetweenTwoNumbers=abs(firstNumber-secondNumber)
if(differenceBetweenTwoNumbers==2):
if(isFirstNumberPrime==True and isSecondNumberPrime==True):
print(firstNumber,"and",secondNumber," are Twin prime number")
else:
print(firstNumber, "and", secondNumber, " are not Twin prime number")
else:
print(firstNumber, "and", secondNumber, " are not Twin prime number")