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

User-Defined Methods in Java for ICSE Class 10: Parameters, Return and Overloading
ICSE Class 10 Computer Applications notes on user-defined methods: method prototype and signature, formal and actual parameters, return types, call by value vs call by reference, pure and impure methods, static methods and method overloading, with programs.

String Methods in Java for ICSE Class 10: 25 Output Questions with Answers
ICSE Class 10 Computer Applications practice on String class methods: length, charAt, indexOf, lastIndexOf, substring, replace, trim, compareTo, equals and more, with 25 board-style output questions and step-by-step answers.

Special Number Programs in Java for ICSE: Armstrong, Spy, Neon, Disarium, Pronic and More
Every special number asked in ICSE Computer Applications – prime, perfect, Armstrong, palindrome, automorphic, neon, spy, Niven, duck, buzz, Disarium, special and pronic numbers – with definitions, examples and one complete Java program that checks them all.