**Question:**

Write a Program in Java to print all the **Twin Prime** numbers within a given range.

**Note:** Twin Prime numbers are a pair of numbers which are both prime and their difference is 2.

**Example:** Twin Prime numbers in the range 1 to 100 are :

(3,5) (5,7) (11,13) (17,19) (29,31) (41,43) (59,61) (71,73)

**Programming Code:**

/**

* The class TwinPrimeRange inputs 2 numbers and prints all the

* twin prime numbers within that range

* @author : www.javaforschool.com

* @Program Type : BlueJ Program – Java

*/

import java.io.*;

class TwinPrimeRange

{

boolean isPrime(int n) //funton for checking prime

{

int count=0;

for(int i=1; i<=n; i++)
{
if(n%i == 0)
count++;
}
if(count == 2)
return true;
else
return false;
}
public static void main(String args[]) throws IOException
{
TwinPrimeRange ob = new TwinPrimeRange();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the lower range : ");
int p = Integer.parseInt(br.readLine());
System.out.print("Enter the upper range : ");
int q = Integer.parseInt(br.readLine());
if(p>q)

System.out.println(“Invalid Range !”);

else

{

System.out.println(“nThe Twin Prime Numbers within the given range are : “);

for(int i=p; i<=(q-2); i++)
{
if(ob.isPrime(i) == true && ob.isPrime(i+2) == true)
{
System.out.print("("+i+","+(i+2)+") ");
}
}
}
}
}[/java]

**Output:**

Enter the lower range : 1

Enter the upper range : 200

The Twin Prime Numbers within the given range are :

(3,5) (5,7) (11,13) (17,19) (29,31) (41,43) (59,61) (71,73) (101,103) (107,109) (137,139) (149,151) (179,181) (191,193) (197,199)

What is the difference between = and ==?

= is assignment operator which assigns the value on the right hand side to the variable on the left hand side.

Example: a = 5 will assign variable ‘a’ with a value 5.

== is relational operator which checks whether the value on the left hand side is equal to the value on the right hand side or not.

Example: a == 5 checks if a is equal to 5 or not.

why d loop is till q-2… logic…..??

because if you are told to find twin primes from 1 to 100 and if you run the loop till hundred, you will be checking 2 numbers (99, 101) and (100, 102) which are out of range.

So, if you go till, 98, you will be checking (98, 100) and then stop.

nice program….