Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Difference between the largest and the smallest primes in an array in Java
Given an array of integers (all elements less than 1,000,000), find the difference between the largest and smallest prime numbers in the array.
Worked Example
Array: [1, 2, 3, 4, 5] Primes in array: 2, 3, 5 Largest Prime = 5 Smallest Prime = 2 Difference = 5 - 2 = 3
Solution Approach
Use the Sieve of Eratosthenes to pre-compute all prime numbers up to 1,000,000. Then scan the array to find the largest and smallest primes and return their difference. The sieve runs in O(n log log n) time and the array scan runs in O(n), making this approach very efficient.
Java Implementation
The following program implements this approach ?
public class JavaTester {
static int MAX = 1000000;
static boolean prime[] = new boolean[MAX + 1];
public static void runSieveOfEratosthenes() {
for (int i = 0; i < MAX + 1; i++) prime[i] = true;
prime[0] = false;
prime[1] = false;
for (int p = 2; p * p <= MAX; p++) {
if (prime[p]) {
for (int i = p * 2; i <= MAX; i += p)
prime[i] = false;
}
}
}
public static int difference(int arr[]) {
int min = MAX + 2;
int max = -1;
for (int i = 0; i < arr.length; i++) {
if (prime[arr[i]]) {
if (arr[i] > max) max = arr[i];
if (arr[i] < min) min = arr[i];
}
}
return max - min;
}
public static void main(String args[]) {
runSieveOfEratosthenes();
int arr1[] = {1, 2, 3, 4, 5};
System.out.println("Array 1 difference: " + difference(arr1));
int arr2[] = {10, 13, 17, 21, 29, 4};
System.out.println("Array 2 difference: " + difference(arr2));
}
}
The output of the above code is ?
Array 1 difference: 3 Array 2 difference: 16
Conclusion
The Sieve of Eratosthenes efficiently pre-computes all primes, allowing O(1) prime checks for each array element. This makes finding the largest and smallest primes in any array a fast O(n) operation after the one-time sieve computation.
