
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Maximum Difference Between Prime Numbers in Given Ranges in C++
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
#include <bits/stdc++.h> using namespace std; bool primeNumber[100005] ; void findPrimes(){ memset(primeNumber, true, sizeof(primeNumber)); for (int i = 2; i * i < 100005; i++) { if (primeNumber[i]) { for (int j = i + i; j < 100005; j += i) primeNumber[j] = false; } } } int findPrimeInRange(int L, int R) { int LPrime = 0; int RPrime = 0; for(int i = L; i <= R; i++){ if(primeNumber[i] == true){ LPrime = i; break; } } for(int j = R; j >= L; j--){ if(primeNumber[j] == true){ 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])<<"\n"; 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
Advertisements