- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to find the Maximum Prime Difference
The Maximum Prime Difference is a problem used to determine the largest difference between indices of two prime numbers in a given array.
Problem Statement
Here, we have given an array of integers as nums. our task is to find the maximum prime difference between the indices of any two prime numbers in an array.
In the given array if we have only one prime number then it returns 0 and if no prime number returns -1.
Example Scenario 1
Input: arr = [11, 4, 7, 6, 13]
Output: 4
The prime numbers are 11 (index 0), 7 (index 2), and 13 (index 4). The maximum difference between their indices is |4 - 0| = 4.
Example Scenario 2
Input: arr = [8, 10, 15, 20]
Output: -1
There is no prime number. So the output is -1.
Example Scenario 3
Input: arr = [8, 17, 6, 23, 5, 29, 31]
Output: 5
The prime numbers are 17 (index 1), 23 (index 3), 5 (index 4), 29 (index 5), and 31 (index 6). The maximum difference between their indices is |6 - 1| = 5.
Example Scenario 4
Input: arr = [4, 6, 8, 10, 13]
Output: 0
In this example there is only one prime number 13 (index 4), The maximum difference between their indices is |4 - 4| = 0.
To solve this problem in various programming languages, here are the two important approaches.
- Sieve with Scan
- Prime Check with Two Pointers
Sieve with Scan
Example
We use this approach to find all prime numbers up to the maximum value in the array. Then, we iterate through the array to find the indices of these prime numbers and calculate the maximum difference between them. The time complexity is O(n \log \log n) + O(m). where n is the length and m is the maximum value in the array.
#include <iostream> #include <vector> #include <cmath> #include <algorithm> using namespace std; vector<bool> sieve(int max_val) { vector<bool> is_prime(max_val + 1, true); is_prime[0] = is_prime[1] = false; for (int i = 2; i <= sqrt(max_val); ++i) { if (is_prime[i]) { for (int j = i * i; j <= max_val; j += i) { is_prime[j] = false; } } } return is_prime; } int maxPrimeDifference(const vector<int>& arr) { int max_val = *max_element(arr.begin(), arr.end()); vector<bool> is_prime = sieve(max_val); vector<int> prime_indices; for (int i = 0; i < arr.size(); ++i) { if (is_prime[arr[i]]) { prime_indices.push_back(i); } } if (prime_indices.size() < 2) return -1; return prime_indices.back() - prime_indices.front(); } int main() { vector<int> arr = {8, 17, 6, 23, 5, 29, 31}; cout << "Maximum Prime Difference = " << maxPrimeDifference(arr) << endl; return 0; }
Output
Maximum Prime Difference = 5
import java.util.*; public class MaxPrimeDifference { public static boolean[] sieve(int maxVal) { boolean[] isPrime = new boolean[maxVal + 1]; Arrays.fill(isPrime, true); isPrime[0] = isPrime[1] = false; for (int i = 2; i <= Math.sqrt(maxVal); i++) { if (isPrime[i]) { for (int j = i * i; j <= maxVal; j += i) { isPrime[j] = false; } } } return isPrime; } public static int maxPrimeDifference(int[] arr) { int maxVal = Arrays.stream(arr).max().getAsInt(); boolean[] isPrime = sieve(maxVal); List<Integer> primeIndices = new ArrayList<>(); for (int i = 0; i < arr.length; i++) { if (isPrime[arr[i]]) { primeIndices.add(i); } } if (primeIndices.size() < 2) return -1; return primeIndices.get(primeIndices.size() - 1) - primeIndices.get(0); } public static void main(String[] args) { int[] arr = {8, 17, 6, 23, 5, 29, 31}; System.out.println("Maximum Prime Difference = " + maxPrimeDifference(arr)); } }
Output
Maximum Prime Difference = 5
def sieve(max_val): is_prime = [True] * (max_val + 1) is_prime[0] = is_prime[1] = False for i in range(2, int(max_val**0.5) + 1): if is_prime[i]: for j in range(i * i, max_val + 1, i): is_prime[j] = False return is_prime def max_prime_difference(arr): max_val = max(arr) is_prime = sieve(max_val) prime_indices = [i for i, num in enumerate(arr) if is_prime[num]] if len(prime_indices) < 2: return -1 return prime_indices[-1] - prime_indices[0] arr = [8, 17, 6, 23, 5, 29, 31] print("Maximum Prime Difference = ", max_prime_difference(arr))
Output
Maximum Prime Difference = 5
package main import ( "fmt" "math" ) func sieve(maxVal int) []bool { isPrime := make([]bool, maxVal+1) for i := 2; i <= maxVal; i++ { isPrime[i] = true } for i := 2; i <= int(math.Sqrt(float64(maxVal))); i++ { if isPrime[i] { for j := i * i; j <= maxVal; j += i { isPrime[j] = false } } } return isPrime } func maxPrimeDifference(arr []int) int { maxVal := 0 for _, num := range arr { if num > maxVal { maxVal = num } } isPrime := sieve(maxVal) primeIndices := []int{} for i, num := range arr { if isPrime[num] { primeIndices = append(primeIndices, i) } } if len(primeIndices) < 2 { return -1 } return primeIndices[len(primeIndices)-1] - primeIndices[0] } func main() { arr := []int{8, 17, 6, 23, 5, 29, 31} fmt.Println("Maximum Prime Difference = ", maxPrimeDifference(arr)) }
Output
Maximum Prime Difference = 5
Prime Check with Two Pointers
Example
To find the maximum prime difference, you can use a direct prime-checking function to identify prime numbers in the array. Then, use two pointers to track the first and last occurrences of these prime numbers. Finally, calculate the difference between their indices. This approach has a time complexity of O(m\sqrt{k}), where (m) is the length of the array and (k) is the average value of the elements in the array.
#include <iostream> #include <vector> #include <cmath> using namespace std; bool isPrime(int num) { if (num <= 1) return false; for (int i = 2; i <= sqrt(num); ++i) { if (num % i == 0) return false; } return true; } int maxPrimeDifference(const vector<int>& arr) { int first = -1, last = -1; for (int i = 0; i < arr.size(); ++i) { if (isPrime(arr[i])) { if (first == -1) first = i; last = i; } } if (first == -1 || last == -1 || first == last) return -1; return last - first; } int main() { vector<int> arr = {8, 17, 6, 23, 5, 29, 31}; cout << "Maximum Prime Difference = " << maxPrimeDifference(arr) << endl; return 0; }
Output
Maximum Prime Difference = 5
public class MaxPrimeDifference { public static boolean isPrime(int num) { if (num <= 1) return false; for (int i = 2; i <= Math.sqrt(num); i++) { if (num % i == 0) return false; } return true; } public static int maxPrimeDifference(int[] arr) { int first = -1, last = -1; for (int i = 0; i < arr.length; i++) { if (isPrime(arr[i])) { if (first == -1) first = i; last = i; } } if (first == -1 || last == -1 || first == last) return -1; return last - first; } public static void main(String[] args) { int[] arr = {8, 17, 6, 23, 5, 29, 31}; System.out.println("Maximum Prime Difference = " + maxPrimeDifference(arr)); } }
Output
Maximum Prime Difference = 5
import math def is_prime(num): if num <= 1: return False for i in range(2, int(math.sqrt(num)) + 1): if num % i == 0: return False return True def max_prime_difference(arr): first = last = -1 for i, num in enumerate(arr): if is_prime(num): if first == -1: first = i last = i if first == -1 or last == -1 or first == last: return -1 return last - first arr = [8, 17, 6, 23, 5, 29, 31] print("Maximum Prime Difference = ", max_prime_difference(arr))
Output
Maximum Prime Difference = 5
package main import ( "fmt" "math" ) func isPrime(num int) bool { if num <= 1 { return false } for i := 2; i <= int(math.Sqrt(float64(num))); i++ { if num%i == 0 { return false } } return true } func maxPrimeDifference(arr []int) int { first, last := -1, -1 for i, num := range arr { if isPrime(num) { if first == -1 { first = i } last = i } } if first == -1 || last == -1 || first == last { return -1 } return last - first } func main() { arr := []int{8, 17, 6, 23, 5, 29, 31} fmt.Println("Maximum Prime Difference = ", maxPrimeDifference(arr)) }
Output
Maximum Prime Difference = 5