1. Overview
Finding the largest prime less than a given number is a classic problem in computer science and mathematics.
In this short tutorial, we’ll explore two approaches to solve this problem in Java.
2. Use Brute Force
Let’s begin with the most straightforward way. We can find the largest prime under a given number by iterating backward from the given number until we find a prime. For each number, we check if it’s prime by verifying that it’s not divisible by any number less than itself except 1:
public static int findByBruteForce(int n) {
for (int i = n - 1; i >= 2; i--) {
if (isPrime(i)) {
return i;
}
}
return -1; // Return -1 if no prime number is found
}
public static boolean isPrime(int number) {
for (int i = 2; i <= Math.sqrt(number); i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
The time complexity of the isPrime() method is O(√N), and we might need to check up to n numbers. Thus, the time complexity of this solution is O(N √N).
3. Use Sieve of Eratosthenes Algorithm
A more efficient way to find the most significant prime number under a given number is using the Sieve of Eratosthenes algorithm. This algorithm efficiently considers all prime numbers up to a given limit. Once we have all prime numbers, we can easily find the largest prime less than the given number:
public static int findBySieveOfEratosthenes(int n) {
boolean[] isPrime = new boolean[n];
Arrays.fill(isPrime, true);
for (int p = 2; p*p < n; p++) {
if (isPrime[p]) {
for (int i = p * p; i < n; i += p) {
isPrime[i] = false;
}
}
}
for (int i = n - 1; i >= 2; i--) {
if (isPrime[i]) {
return i;
}
}
return -1;
}
This time, we use the same isPrime() method in the first solution. Our code follows three basic steps:
- Initialize a boolean array isPrime[] to track prime status for numbers up to n, defaulting to true.
- For each prime p, mark its multiples as non-prime (false) starting from p*p to n. This efficiently filters out non-prime numbers.
- Iterate backward from n-1 to find the highest index marked true.
The time complexity of the Sieve of Eratosthenes is O(N log (log (N))), which is much more efficient than the brute force approach for large n.
4. Conclusion
In this tutorial, we’ve explored two ways to find the largest prime in Java under the given number. The brute force method is more straightforward but less efficient. The Sieve of Eratosthenes offers a more efficient solution with a time complexity of O(n log log n), making it the preferred choice for more significant numbers.
The example code from this article can be found over on GitHub.