Twin Prime Numbers in Java — Definition, Examples and Program
Twin prime numbers are pairs of prime numbers that have a difference of exactly 2. In other words, if p and p+2 are both prime, they form a twin prime pair.
Examples of Twin Prime Numbers
- (3, 5)
- (5, 7)
- (11, 13)
- (17, 19)
How to Check Twin Primes?
- Take a number as input.
- Check if the number is prime.
- Check if the number + 2 is also prime.
- If both are prime → They form a twin prime pair.
Java Program to Check Twin Prime Numbers
import java.util.Scanner;
public class TwinPrime {
// Function to check if a number is prime
public static boolean isPrime(int num) {
if (num <= 1) return false;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) return false;
}
return true;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
if (isPrime(num) && isPrime(num + 2)) {
System.out.println(num + " and " + (num + 2) + " are Twin Prime Numbers");
} else {
System.out.println(num + " and " + (num + 2) + " are NOT Twin Prime Numbers");
}
}
}
Sample Output
Enter a number: 5
5 and 7 are Twin Prime Numbers
Enter a number: 14
14 and 16 are NOT Twin Prime Numbers
Practice Challenges
- Write a program to print all twin prime pairs between 1 and 100.
- Modify the program to find twin prime pairs where both numbers are greater than a user-specified number N.
- Check if a given number is part of any twin prime pair.
Twin prime numbers are interesting in number theory and are studied for their distribution among prime numbers. This Java program helps you quickly identify twin primes using efficient prime checking.