Below here, you will find my implementation of Sieve of Eratosthenes algorithm for finding prime numbers between 1 and 250000 and also how I make use of it, to filter out all the prime number ending in 7.
The overall time complexity of this algorithm is O(N) because all the implementation is done in sieve algo.
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
int N = 250000;
ArrayList<Integer> primeWithEnding7 = new ArrayList<Integer>();
int maxPrimeNum7 = 0;
boolean[] isPrime = new boolean[N + 1];
for (int i = 2; i <= N; i++) {
isPrime[i] = false;
}
for (int i = 2; i <= N; i++) {
if (!isPrime[i]) {
int rem = i%10;
if(rem == 7) {
maxPrimeNum7 = Math.max(maxPrimeNum7, i);
primeWithEnding7.add(i);
}
for (int j = i+i; j <= N; j+=i) {
isPrime[j] = true;
}
}
}
// Print all the prime numbers ending in 7
for(int i: primeWithEnding7) {
System.out.print(i + " ");
}
System.out.println();
System.out.println("Max number is " + maxPrimeNum7);
}
}
Now let's take an example to understand why this algorithm will work for us.
So let's suppose N = 30. Now when the loop starts from 2, if 7 was not prime it would have been covered as non-prime in the inner loop j, the fact that i reaches to 7 proves that it's a prime number, So I keep a global array list as my data structure to add only those prime numbers that end in 7 and because I use % operator to calculate the last digit of the number, the time complexity of that step is O(1), so total time complexity of the algorithm comes to O(N).
Let me know, if I have made any mistake in the algorithm, I will fix it.
Hope this helps!