Solution of 10394 - Twin Primes

Problem Description
source:https://uva.onlinejudge.org/external/103/10394.html

Twin primes are pairs of primes of the form (p, p + 2). The term “twin prime” was coined by Paul Stckel (1892-1919). The first few twin primes are (3, 5), (5, 7), (11, 13), (17, 19), (29, 31), (41, 43). In this problem you are asked to find out the S-th twin prime pair where S is an integer that will be given in the input.

Input 

The input will contain less than 10001 lines of input. Each line contains an integers S (1 ≤ S ≤ 100000), which is the serial number of a twin prime pair. Input file is terminated by end of file. 

Output 

For each line of input you will have to produce one line of output which contains the S-th twin prime pair. The pair is printed in the form (p1,¡space¿p2). Here ¡space¿ means the space character (ASCII 32) . You can safely assume that the primes in the 100000-th twin prime pair are less than 20000000.  

Sample Input 






Sample Output 

(3, 5) 
(5, 7)
(11, 13) 
(17, 19)

Solution:
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <deque>
#include <fstream>
#include <iostream>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
#include<stdio.h>
#include<stdlib.h>
#define max 20000000

using namespace std;

long long int prime[max],thprime[max];

void GenPrime()
{
    long long int i,j,m,k=0,t;
    m=(long long int)sqrt(max);
    memset(prime, 1, sizeof(prime));
    memset(thprime, 0, sizeof(thprime));
    prime[0]=prime[1]=0;
    for(i=2;i<=m;i++)
    {
        if(prime[i])
        {
            if(prime[i+2])
                thprime[k++]=i;
            for(j=i+i;j<max;j+=i)
                prime[j]=0;
        }

    }
    t=max/13;
    t*=12;
    for(i=m+1;i<=t;i++)
    {
        if(prime[i] && prime[i+2] )
            thprime[k++]=i;
    }
}
int main()
{
    long long int n;
    GenPrime();
    //freopen("in.txt","r",stdin);
    while(scanf("%lld",&n)==1)
    {
        printf("(%lld, %lld)\n",thprime[n],thprime[n]+2);
    }
    return 0;
}
image

No comments:

Post a Comment

Write your comment - Share Knowledge and Experience