Open In App

Queries for maximum difference between prime numbers in given ranges

Last Updated : 01 Jun, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Given n queries of the form range [L, R]. The task is to find the maximum difference between two prime numbers in the range for each query. If there are no prime in the range then print 0. All ranges are below 100005.

Examples: 

Input : Q = 3
        query1 = [2, 5]
        query2 = [2, 2]
        query3 = [24, 28]
Output : 3
         0
         0
In first query, 2 and 5 are prime number 
in the range with maximum difference which 
is 3. In second there 
is only 1 prime number in range, so output
is 0. And in third query, there is no prime number in the given range so the output is 0.

The idea is to compute Prime numbers using Sieve of Eratosthenes along with some precomputing. 

Below are the step to solve the question: 
Step 1: Find the prime numbers using Sieve of Eratosthenes algorithm. 
Step 2: Make an array, let say prefix[], where prefix[i] represents largest prime number smaller or equal to i. 
Step 3: Make an array, let say suffix[], where suffix[i] represents smallest prime number greater or equal to i. 
Step 4: Now for each query having [L, R], do the following:

  if (prefix[R]  R)
    return 0;
  else
    return prefix[R] - suffix[L];

Below is the implementation of this approach:  

C++




// CPP program to find maximum differences between
// two prime numbers in given ranges
#include <bits/stdc++.h>
using namespace std;
#define MAX 100005
 
// Declare global variables to assign heap memory and avoid
// stack overflow
bool prime[MAX];
int prefix[MAX], suffix[MAX];
 
// Precompute Sieve, Prefix array, Suffix array
void precompute(int prefix[], int suffix[])
{
    memset(prime, true, sizeof(prime));
 
    // Sieve of Eratosthenes
    for (int i = 2; i * i < MAX; i++) {
        if (prime[i]) {
            for (int j = i * i; j < MAX; j += i)
                prime[j] = false;
        }
    }
 
    prefix[1] = 1;
    suffix[MAX - 1] = 1e9 + 7;
 
    // Precomputing Prefix array.
    for (int i = 2; i < MAX; i++) {
        if (prime[i])
            prefix[i] = i;
        else
            prefix[i] = prefix[i - 1];
    }
 
    // Precompute Suffix array.
    for (int i = MAX - 1; i > 1; i--) {
        if (prime[i])
            suffix[i] = i;
        else
            suffix[i] = suffix[i + 1];
    }
}
 
// Function to solve each query
int query(int prefix[], int suffix[], int L, int R)
{
    if (prefix[R] < L || suffix[L] > R)
        return 0;
    else
        return prefix[R] - suffix[L];
}
 
// Driven Program
int main()
{
    int q = 3;
    int L[] = { 2, 2, 24 };
    int R[] = { 5, 2, 28 };
 
    precompute(prefix, suffix);
 
    for (int i = 0; i < q; i++)
        cout << query(prefix, suffix, L[i], R[i]) << endl;
 
    return 0;
}


Java




// Java program to find maximum differences between
// two prime numbers in given ranges
 
public class GFG {
 
    final static int MAX = 100005;
 
    // Precompute Sieve, Prefix array, Suffix array
    static void precompute(int prefix[], int suffix[])
    {
        boolean prime[] = new boolean[MAX];
        for (int i = 0; i < MAX; i++) {
            prime[i] = true;
        }
 
        // Sieve of Eratosthenes
        for (int i = 2; i * i < MAX; i++) {
            if (prime[i]) {
                for (int j = i * i; j < MAX; j += i) {
                    prime[j] = false;
                }
            }
        }
 
        prefix[1] = 1;
        suffix[MAX - 1] = (int)1e9 + 7;
 
        // Precomputing Prefix array.
        for (int i = 2; i < MAX; i++) {
            if (prime[i]) {
                prefix[i] = i;
            }
            else {
                prefix[i] = prefix[i - 1];
            }
        }
 
        // Precompute Suffix array.
        for (int i = MAX - 2; i > 1; i--) {
            if (prime[i]) {
                suffix[i] = i;
            }
            else {
                suffix[i] = suffix[i + 1];
            }
        }
    }
 
    // Function to solve each query
    static int query(int prefix[], int suffix[], int L,
                     int R)
    {
        if (prefix[R] < L || suffix[L] > R) {
            return 0;
        }
        else {
            return prefix[R] - suffix[L];
        }
    }
 
    // Driven Program
    public static void main(String[] args)
    {
        int q = 3;
        int L[] = { 2, 2, 24 };
        int R[] = { 5, 2, 28 };
 
        int prefix[] = new int[MAX], suffix[]
                                     = new int[MAX];
        precompute(prefix, suffix);
 
        for (int i = 0; i < q; i++) {
            System.out.println(
                query(prefix, suffix, L[i], R[i]));
        }
    }
}
/*This code is contributed by Rajput-Ji*/


Python3




# Python 3 program to find maximum
# differences between two prime numbers
# in given ranges
from math import sqrt
 
MAX = 100005
 
# Precompute Sieve, Prefix array, Suffix array
def precompute(prefix, suffix):
    prime = [True for i in range(MAX)]
 
    # Sieve of Eratosthenes
    k = int(sqrt(MAX))
    for i in range(2, k, 1):
        if (prime[i]):
            for j in range(i * i, MAX, i):
                prime[j] = False
 
    prefix[1] = 1
    suffix[MAX - 1] = int(1e9 + 7)
 
    # Precomputing Prefix array.
    for i in range(2, MAX, 1):
        if (prime[i]):
            prefix[i] = i
        else:
            prefix[i] = prefix[i - 1]
 
    # Precompute Suffix array.
    i = MAX - 2
    while(i > 1):
        if (prime[i]):
            suffix[i] = i
        else:
            suffix[i] = suffix[i + 1]
        i -= 1
 
# Function to solve each query
 
 
def query(prefix, suffix, L, R):
    if (prefix[R] < L or suffix[L] > R):
        return 0
    else:
        return prefix[R] - suffix[L]
 
 
# Driver Code
if __name__ == '__main__':
    q = 3
    L = [2, 2, 24]
    R = [5, 2, 28]
 
    prefix = [0 for i in range(MAX)]
    suffix = [0 for i in range(MAX)]
    precompute(prefix, suffix)
 
    for i in range(0, q, 1):
        print(query(prefix, suffix,
                    L[i], R[i]))
 
# This code is contributed by
# Surendra_Gangwar


C#




// C# program to find maximum differences between
// two prime numbers in given ranges
using System;
 
public class GFG {
 
    static readonly int MAX = 100005;
 
    // Precompute Sieve, Prefix array, Suffix array
    static void precompute(int[] prefix, int[] suffix)
    {
        bool[] prime = new bool[MAX];
        for (int i = 0; i < MAX; i++) {
            prime[i] = true;
        }
 
        // Sieve of Eratosthenes
        for (int i = 2; i * i < MAX; i++) {
            if (prime[i]) {
                for (int j = i * i; j < MAX; j += i) {
                    prime[j] = false;
                }
            }
        }
 
        prefix[1] = 1;
        suffix[MAX - 1] = (int)1e9 + 7;
 
        // Precomputing Prefix array.
        for (int i = 2; i < MAX; i++) {
            if (prime[i]) {
                prefix[i] = i;
            }
            else {
                prefix[i] = prefix[i - 1];
            }
        }
 
        // Precompute Suffix array.
        for (int i = MAX - 2; i > 1; i--) {
            if (prime[i]) {
                suffix[i] = i;
            }
            else {
                suffix[i] = suffix[i + 1];
            }
        }
    }
 
    // Function to solve each query
    static int query(int[] prefix, int[] suffix, int L,
                     int R)
    {
        if (prefix[R] < L || suffix[L] > R) {
            return 0;
        }
        else {
            return prefix[R] - suffix[L];
        }
    }
 
    // Driven Program
    public static void Main()
    {
        int q = 3;
        int[] L = { 2, 2, 24 };
        int[] R = { 5, 2, 28 };
 
        int[] prefix = new int[MAX];
        int[] suffix = new int[MAX];
        precompute(prefix, suffix);
 
        for (int i = 0; i < q; i++) {
            Console.WriteLine(
                query(prefix, suffix, L[i], R[i]));
        }
    }
}
 
/*This code is contributed by 29AjayKumar*/


PHP




<?php
// PHP program to find maximum differences
// between two prime numbers in given ranges
$MAX = 100005;
 
// Precompute Sieve, Prefix array,
// Suffix array
function precompute(&$prefix, &$suffix)
{
    global $MAX;
    $prime = array_fill(0, $MAX, true);
 
    // Sieve of Eratosthenes
    for ($i = 2; $i * $i < $MAX; $i++)
    {
        if ($prime[$i])
        {
            for ($j = $i * $i;
                 $j < $MAX; $j += $i)
                $prime[$j] = false;
        }
    }
 
    $prefix[1] = 1;
    $suffix[$MAX - 1] = 1e9 + 7;
 
    // Precomputing Prefix array.
    for ($i = 2; $i < $MAX; $i++)
    {
        if ($prime[$i])
            $prefix[$i] = $i;
        else
            $prefix[$i] = $prefix[$i - 1];
    }
 
    // Precompute Suffix array.
    for ($i = $MAX - 1; $i > 1; $i--)
    {
        if ($prime[$i])
            $suffix[$i] = $i;
        else
            $suffix[$i] = $suffix[$i + 1];
    }
}
 
// Function to solve each query
function query($prefix, $suffix, $L, $R)
{
    if ($prefix[$R] < $L || $suffix[$L] > $R)
        return 0;
    else
        return $prefix[$R] - $suffix[$L];
}
 
// Driver Code
$q = 3;
$L = array( 2, 2, 24 );
$R = array( 5, 2, 28 );
 
$prefix = array_fill(0, $MAX + 1, 0);
$suffix = array_fill(0, $MAX + 1, 0);
precompute($prefix, $suffix);
 
for ($i = 0; $i < $q; $i++)
    echo query($prefix, $suffix,
               $L[$i], $R[$i]) . "\n";
 
// This code is contributed by mits
?>


Javascript




<script>
 
// JavaScript program to find maximum
// differences between two prime
// numbers in given ranges
 
let MAX = 100005;
  
// Precompute Sieve, Prefix array, Suffix array
function precompute(prefix, suffix)
{
    let prime = [];
    for(let i = 0; i < MAX; i++)
    {
        prime[i] = true;
    }
 
    // Sieve of Eratosthenes
    for(let i = 2; i * i < MAX; i++)
    {
        if (prime[i])
        {
            for(let j = i * i; j < MAX; j += i)
            {
                prime[j] = false;
            }
        }
    }
 
    prefix[1] = 1;
    suffix[MAX - 1] = 1e9 + 7;
 
    // Precomputing Prefix array.
    for(let i = 2; i < MAX; i++)
    {
        if (prime[i])
        {
            prefix[i] = i;
        }
        else
        {
            prefix[i] = prefix[i - 1];
        }
    }
 
    // Precompute Suffix array.
    for(let i = MAX - 2; i > 1; i--)
    {
        if (prime[i])
        {
            suffix[i] = i;
        }
        else
        {
            suffix[i] = suffix[i + 1];
        }
    }
}
 
// Function to solve each query
function query(prefix, suffix, L, R)
{
    if (prefix[R] < L || suffix[L] > R)
    {
        return 0;
    }
    else
    {
        return prefix[R] - suffix[L];
    }
}
 
// Driver Code
let q = 3;
let L = [ 2, 2, 24 ];
let R = [ 5, 2, 28 ];
let prefix = [], suffix = [];
 
precompute(prefix, suffix);
 
for(let i = 0; i < q; i++)
{
    document.write(query(prefix, suffix,
                         L[i], R[i]) + "<br/>");
}
 
// This code is contributed by sanjoy_62
 
</script>


Output: 

3
0
0 


Similar Reads

Queries for maximum and minimum difference between Fibonacci numbers in given ranges
Given an array arr[][] containing N queries of the form [L, R], the task is to find the maximum difference between two Fibonacci numbers in the range for each query. If there are no Fibonacci numbers in the range or only one Fibonacci number, then print 0. Note: All the ranges are below 100005. Examples: Input: N = 2, arr[][] = {{2, 2}, {2, 5}} Out
15 min read
Count numbers in a given range having prime and non-prime digits at prime and non-prime positions respectively
Given two integers L and R, the task is to find the count of numbers in the range [L, R] having prime digits at prime positions and non-prime digits at non-prime positions. Examples: Input: L = 5, R = 22 Output: 7Explanation: The numbers 6, 8, 9, 12, 13, 15, and 17 have prime digits at prime positions and non-prime digits at non-prime positions. In
15 min read
Maximum length intersection of all K ranges among all given ranges
Given an array arr[] consisting of N ranges of the form [L, R], the task is to select K ranges such that the intersection length of the K ranges is maximum. Examples: Input: arr[] = {{5, 15}, {1, 10}, {14, 50}, {30, 70}, {99, 100}}, K = 2Output: 21Explanation: Selecting ranges (14, 50) and (30, 70) would give the maximum answer. Therefore, the maxi
7 min read
Count of ways to select exactly K non-disjoint ranges from given N ranges
Given two arrays L[] and R[] of size N, and an integer K, the task is to find the number of ways to select exact K disjoint ranges formed by taking elements present at the same index from the array L[] and R[]. Examples: Input: N = 7, K = 3, L[] = {1, 3, 4, 6, 1, 5, 8}, R[] = {7, 8, 5, 7, 3, 10, 9}Output: 9Explanation: The possible ways of selectin
10 min read
Queries to find minimum absolute difference between adjacent array elements in given ranges
Given an array arr[] consisting of N integers and an array query[] consisting of queries of the form {L, R}, the task for each query is to find the minimum of the absolute difference between adjacent elements over the range [L, R]. Examples: Input: arr[] = {2, 6, 1, 8, 3, 4}, query[] = {{0, 3}, {1, 5}, {4, 5}}Output:411Explanation:Following are the
21 min read
Choose points from two ranges such that no point lies in both the ranges
Given two segments [L1, R1] and [L2, R2], the task is to choose two elements x and y from both the ranges (one from range one and other from range two) such that no element belongs to both the ranges i.e. x belongs to first range and y belongs to second range. If no such element exists then print -1 instead. Examples: Input: L1 = 1, R1 = 6, L2 = 3,
4 min read
Check if a pair of integers from two ranges exists such that their Bitwise XOR exceeds both the ranges
Given two integers A and B, the task is to check if there exists two integers P and Q over the range [1, A] and [1, B] respectively such that Bitwise XOR of P and Q is greater than A and B. If found to be true, then print "Yes". Otherwise, print "No". Examples: Input: X = 2, Y = 2 Output: YesExplanation:By choosing the value of P and Q as 1 and 2 r
9 min read
Absolute Difference between the Sum of Non-Prime numbers and Prime numbers of an Array
Given an array of positive numbers, the task is to calculate the absolute difference between sum of non-prime numbers and prime numbers. Note: 1 is neither prime nor non-prime. Examples: Input : 1 3 5 10 15 7 Output : 10 Explanation: Sum of non-primes = 25 Sum of primes = 15 Input : 3 4 6 7 Output : 0 Naive Approach: A simple solution is to travers
16 min read
Absolute difference between the Product of Non-Prime numbers and Prime numbers of an Array
Given an array of positive numbers, the task is to calculate the absolute difference between product of non-prime numbers and prime numbers.Note: 1 is neither prime nor non-prime.Examples: Input : arr[] = {1, 3, 5, 10, 15, 7} Output : 45 Explanation : Product of non-primes = 150 Product of primes = 105 Input : arr[] = {3, 4, 6, 7} Output : 3 Naive
15 min read
Absolute difference between the XOR of Non-Prime numbers and Prime numbers of an Array
Given an array arr[] of N positive integers, the task is to calculate the absolute difference between XOR of non-prime numbers and prime numbers. Note that 1 is neither prime nor composite.Examples: Input: arr[] = {1, 3, 5, 10, 15, 7} Output: 4 Xor of non-primes = 10 ^ 15 = 5 Xor of primes = 3 ^ 5 ^ 7 = 1 |5 - 1| = 4Input: arr[] = {3, 4, 6, 7} Outp
8 min read