Twin Prime
Write a program to accept two numbers from the user and print whether they are twin prime number or not. A twin prime is a pair of two numbers that are both prime and their difference is two.
Write a program to accept two numbers from the user and print whether they are twin prime number or not. A twin prime is a pair of two numbers that are both prime and their difference is two.
Example: 11 and 13
import java.io.*;
class Twin_Prime{
public static int prime(int k){
int f=1;
for(int i=2;i<k;i++){
if(k%i==0){
f=0;
}
}
return f;
}
public static void main() throws IOException{
int a1;
int a2;
int j;
int n;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the limit");
n=Integer.parseInt(br.readLine());
System.out.println("Twin primes upto" +n+" are:");
for(int i=2;i<(n-2);i++){
j=i+2;
a1=prime(i);
a2=prime(j);
if(a1==1 && a2==1){
System.out.println(i+"\t"+j);
}
}
}
}Output:
Enter the limit
50
Twin primes upto50 are:
3 5
5 7
11 13
17 19
29 31
41 43
Related Posts
Continue learning with these related articles
Sum of First n Natural Numbers in Java (Loop and Formula)
Find the sum of the first n natural numbers in Java with a for loop, a while loop and the formula n(n + 1)/2, with a dry run and the sums of even numbers, odd numbers, squares and cubes.
Prime Number Program in Java: Check a Number and Print Primes in a Range
Check whether a number is prime in Java by counting its factors, a faster square-root method with isPrime(), and a program that prints all prime numbers in a range.

Encapsulation, Access Specifiers and Scope of Variables in Java for ICSE Class 10
ICSE Class 10 Computer Applications notes on encapsulation: private, default, protected and public access, data hiding with getter and setter methods, instance vs static (class) variables, local variables and scope, with a solved BankAccount program.