Tuesday, January 28, 2020


UVA - 10394 - Twin Primes

Problem link: https://onlinejudge.org/external/103/10394.pdf

Explanation: Precalculate all twin primes.




Code First Then See Solution 


Code: 

#include <bits/stdc++.h>

#define mx 20000009
#define ll long long

using namespace std;

long long int a[mx],b[mx];

int main()
{

    for(ll i=0;i<mx;i++)
        a[i]=0;
    a[0]=a[1]=1;
    for(ll i=4;i<mx;i+=2)
        a[i]=1;
    for(ll i=3;i<sqrt(mx);i+=2)
    {
        if(a[i]==0)
        {
            for(ll j=i*i;j<mx;j+=i)
                a[j]=1;
        }
    }
    ll k=1;
    for(ll i=2;i<mx;i++)
    {
        if(a[i]==0&&a[i+2]==0)
            b[k++]=i;
    }
    ll s;
    while(cin>>s)
    {
        cout<<"("<<b[s]<<", "<<b[s]+2<<")"<<endl;
    }
    return 0;
}

No comments:

Post a Comment