Question
Write c++ code for this problem:
10140 Prime Distance The branch of mathematics called mumber theory is about peoperties of numers Oue o the as that has captured the sterest of umler theoerticinns for thissads o yeus is the queton of geimality. A how dense they are in irs nars. Adjacent primes are two taumlers that air Indh prins, but bere aze no ofher peime saibers between the adjacent peimes Fr esampe, 2,3 are the only adjaent pimes that are also aljace mbers Your program is gven 2 mambens L and U (sL<Us2 147,483, 647), and you are to find the two adjacet primes and Ca (Ls< SU) that are cloest (ie Ca-Ci is the iam) there are other pairs that are the sae distance apart, ue the fit pir Yo ae albo to find the two djacent peimes D wnd DLS DDSU) whee D and D are as distant from each other as possibile (agpin chooeing the first pair if there is a tie). Input Each ine of inpat will conan two ponitive ineges,L and &,with Lc.The disace betwe andU wiall not exceed 1,000000 Output Foe each L and U, the outpat wil eit her be the st atement that there ate soadjet peimes s there are less than two primes between the two given in-det») ot a line givi㎎ tr wo pakB d adrent primes Sample Input Sample Output 2.3 are clopest 7,11 are sost distant There are no adjacent prises
0 0
Add a comment Improve this question Transcribed image text
Answer #1

#include <cstdio>
#include <cmath>
#include <vector>
#include <climits>
/*However instead of declaring all the above library
Include the following
#include<bits/stdc++.h>

This is accepted generally all the online judge.
This will include the function of all standard library.
*/
using namespace std;

bool mk[1000005]; //This is used to mask all the prime no true and no prime false
vector<int> prime; //Vector will store all the prime no

/*
    The following Method implements the "sieve of eranthoses" algorithm
    which is used to calculate all the prime no upto the limit
*/
void sieve(int n){
    //Since 2 is a prime. Simply include it.
    prime.push_back(2);
    int i=3;
    //We only need to check for odd no because no even no will be prime.
    for(i=3;i*i<=n;i+=2){
        /*
        Since mk will only have to check for the odd no
        We can reduce the mk size by half.
        So to check any no, divide (integer division) by half and check that index.
        eg. for 3 check (3/2) = index 1
            for 5 check (5/2) = index 2
            for 7 check (7/2) = index 3
            .
            for n check (n/2) = index floor(n/2)
        */
        /*
            >> is a bitwise operator. It shift the no to the left by 1 bit.
            eg 15: binary representation- 1111
            15 >> 1: shift left by 1 bit-> result: 111 : 7 (half (integer) of 15)
            15 >> 2: shift by 2 bit -> 11

            also 111001111 shift left by 1 -> 11100111
        */
        if(!mk[i>>1]){ //Check if it has not been marked composite
            prime.push_back(i); //push the no in prime vector
            mk[i>>1]=1; // Now mark it has done.
            /*
                Mark all its multiple composite. Note we have to mark only odd multiple.
                Also we can start from i*i because.
                Let i*j be multiple and j < i.
                Since we already have checke for j. No need to check again
            */
            for(int j=i*i;j<=n;j+=2*i){
                mk[j>>1]=1;
            }
        }
    }

    //The above loop was run only till square of the limit.
    /*
        Any largest divisor of any no except itself will be its square root.
        So if any no greater than square root of limit is not marked composite,
        It means it does not have any divisor so far.
        So the only divisor will be itself and 1.
        Push all unmarked in prime.
    */
    for(;i<=n;i+=2){
        if(!mk[i>>1]) prime.push_back(i);
    }
}

bool check_prime(int n) {
    //1 is not prime and 2 is prime.
    if(n == 1) return 0;
    if(n == 2) return 1;
    int sq = sqrt(n) + 1; //We need to check only till square root of no. If no divisor till here, then it will be prime. Logic written in above function.
    int sz = prime.size();
    for(int i = 0; i < sz && prime[i] < sq; i++){ //Iterate to all prime less than the square root.
        /*
            Note if n is prime, this loop will run till sqrt(n).
            eg. n=3, then i will be less than 2 always
            n = 13, then i will always be less than sqrt(13) + 1 = 3 + 1 = 4
        */
        if(n % prime[i] == 0) return 0; //If it is divisible by prime, then its not prime.
    }
    //If its not yet divisible by any prime less than or equal to its square root. Its prime.
    return 1;
}

int main(){
    /*
    The upper limit is 2, 147483647
    (10^6)^2 = 10^12
    the square root of limit is always less than 10^6.
    So we store all the prime less than or equat to 10^6
    */
    sieve(1e6);
    long long l, u;
    /*
        The following will keep on taking input if it is present in the file or input stream
    */
    while(scanf("%lld %lld", &l, &u) == 2){

        int last = -1; //Stores the last prime encountered
        int close_l, close_u, dist_u, dist_l; //Store the pair which are closest and distant respectively. l- lower no, u-upper no
        int cl = INT_MAX, dis = INT_MIN; //cl: closest distance, dis: maximum distant. Initialise by maximum and minimum no respectively.
        bool flag = 0; //if it is 1 then we have encounterd a pair
        for ( long long i = l ; i <= u; i++){
            if(check_prime(i)){ // Check if it is prime
                if(last == -1){ //Whether we have encounterd any prime or not.
                    last = i;
                } else{ //If there is a prime encountered before.
                    //Set flag as true, ie. we have found a pair
                    flag = 1;
                    //Calculate distance
                    int d = i - last;
                    if (d < cl){ //If its smaller than closest, update
                        close_l = last;
                        close_u = i;
                        cl = d;
                    }
                    if ( d > dis){ //If its greater than largest, update
                        dist_l = last;
                        dist_u = i;
                        dis = d;
                    }
                    last = i;
                }
            }
        }
        if (flag) {
            printf("%d,%d are closest, %d,%d are most distant.\n", close_l, close_u, dist_l, dist_u);
        } else{
            printf("There are no adjacent primes.\n");
        }
    }
    return 0;
}

The above code will give the solution

Add a comment
Know the answer?
Add Answer to:
Write c++ code for this problem: 10140 Prime Distance The branch of mathematics called mumber theory...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT