# Queries for maximum difference between prime numbers in given ranges in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

Best Seller

66 Lectures 5.5 hours

In this problem, we are given Q queries that consist of two values L and R. Our task is to create a program to solve Queries for maximum difference between prime numbers in given ranges in C++.

Problem description: Here, in each querry, we are given two values L and R. We have to find the maximum difference i.e. the difference between the largest and the smallest prime numbers within the given range.

Let’s take an example to understand the problem,

## Input

Q = 2
2 45
14 16
41 0

## Output

### Explanation

For query 1, the smallest prime number within the given range is 2 and the biggest one is 43. The difference 43 - 2 = 41.

For query 2, there is no prime number within the given range, hence the output is 0.

## Solution approach,

To solve the problem, we will create an array of prime numbers till 100005
which is the given range. Then, we will find the first prime number which is
greater than L and the first prime number which is smaller than R . and find
their difference.

Program to illustrate the working of our solution,

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;

void findPrimes(){
for (int i = 2; i * i < 100005; i++) {
for (int j = i + i; j < 100005; j += i)
}
}
}

int findPrimeInRange(int L, int R) {

int LPrime = 0;
int RPrime = 0;
for(int i = L; i <= R; i++){
LPrime = i;
break;
}
}
for(int j = R; j >= L; j--){
RPrime = j;
break;
}
}
return (RPrime - LPrime);
}

int main() {
int Q = 3;
int query[Q][2] = {{4, 15}, {32, 37}, {54, 1100}};
findPrimes();
for (int i = 0; i < Q; i++)
cout<<"For query "<<(i+1)<<": The maximum difference between primes numbers is "<<findPrimeInRange(query[i][0], query[i][1])<<"";
return 0;
}

## Output

For query 1: The maximum difference between primes numbers is 8
For query 2: The maximum difference between primes numbers is 0
For query 3: The maximum difference between primes numbers is 1038
Updated on 09-Sep-2020 07:50:10