HackerRank : Week of Code 26 – Twins

By | November 30, 2016

Lia is fascinated by anything she considers to be a twin. She calls a pairs of positive integers, i and j , twins if:

  • They are both prime. A prime number is an integer greater than 1 that has no positive divisors other than 1 and itself.
  • Their absolute difference is exactly equal to 2  (i.e.|j-i|=2 ).

Given an inclusive interval of integers from n to m, can you help Lia find the number of pairs of twins there are in the interval (i.e.,[n,m] )? Note that pairs (i,j) and (j,i) are considered to be the same pair.

Input Format

Two space-separated integers describing the respective values of n and m.


 1<= n <=m <= 10^9
m – n <= 10^6

Output Format

Print a single integer denoting the number of pairs of twins.

Sample Input 0

3 13

Sample Output 0


Explanation 0

There are three pairs of twins: (3,5), (5,7) and (11,13).


Taken both the inputs from user.
Now I have run loop inclusively between both the inputs.
If the variable loop integer is a prime number then I have added it in a TreeSet.

Now I have traversed the TreeSet and if the difference between 2 consecutive
integers is 2 then I have increased a count variable.

This count variable is final solution.

public class Twins {
	public static boolean isPrime(int n)
	     if (n <= 1)  return false;
	    if (n <= 3)  return true;
	    if (n%2 == 0 || n%3 == 0) return false;
	    for (int i=5; i*i<=n; i=i+6)
	        if (n%i == 0 || n%(i+2) == 0)
	           return false;
	    return true;
	public static void main(String[] args) {
		Scanner scan= new Scanner(System.in);	
		int a=scan.nextInt(), b=scan.nextInt();	
		Set set= new TreeSet();	
		for(int i=a;i<=b;i++)
		int prev=0, count=0;
		for (Integer integer : set)