Friday, April 29, 2011

WAP to find Nth Twin prime Efficiently-UnSolved Problem In Mathematics In Prime Number Theory

You will have to take an integer n as input. and output should be the nth twin prime pair

A twin prime is a prime number that differs from another prime number by two. Except for the pair (2, 3), this is the smallest possible difference between two primes. Some examples of twin prime pairs are (3, 5), (5, 7), (11, 13), (17, 19), (29, 31) and (41, 43). Sometimes the term twin prime is used for a pair of twin primes; an alternative name for this is prime twin.


public class TwinPrime {

public static void main(String a[])
{
boolean flag=false; int i,n=10024;
boolean k=false;
for(i=3;n>0;i+=2)
{
k=isPRIME(i)==true && isPRIME(i+2)==true;
if(k)
n--;
//System.out.println( "" + i + "" + (i+2));
}
System.out.println("Twins Prime are:" + (i-2) + ":" + i);
}

static boolean isPRIME(int x)
{
int i=0;
if(x <= 1)
return false;
int s = (int)Math.sqrt(x);
for(i = 2; i <= s; i++)
if(x%i == 0)
{
//System.out.println("" + x + "is prime" );
return false;
}
return true;
}


}

List : http://primes.utm.edu/lists/small/100ktwins.txt
Run Here http://ideone.com/TeJKSv

2 comments :

Nope said...

This can be done in O(1) using the following approach .

Every prime number if of form 6n+-1
And each of these will give me a pair of prime number , thus we need to just put the value of n in the above relation to obtain the twin primes and the difference b/w them will be two

I have verified it form test cases upto 42,43 .Please correct me if im wrong .

Unknown said...

@richi yes i know 6n+1 but there many diff. theorem that can say for particular limit so according to u when for 4th prime we put n=4 & we get 6*4+1 (25 not prime )& 6*4-1(23 prime ) but both are are not twin prime as 25 is not prime & as u said Euler 6n+1 theorem will in several cases so actual answer is (17 ,19) that's what i explained do notify me if something missed ?

Shashank