How to Generate Twin Primes and Implement Basic Sorting in Java
This article shows how to generate prime numbers using a recursive list‑filtering method, find all twin primes below 10,000, and provides complete Java implementations of bubble sort and insertion sort for educational purposes.
Prime generation via recursive filtering
The algorithm builds a list of integers up to a given limit (e.g., 10,000) and then recursively removes any element that is divisible by the current prime candidate. After each pass the next element in the list becomes the new divisor, and the process repeats until the end of the list is reached, leaving only prime numbers.
static void get(List<Integer> list, int tt) {
int num = list.get(tt);
for (int i = tt + 1; i < list.size(); i++) {
if (list.get(i) % num == 0) {
list.remove(i--);
}
}
if (list.size() > ++tt) {
get(list, tt);
}
}Twin‑prime detection
After the sieve finishes, the program scans the resulting list of primes. Adjacent entries whose difference equals 2 constitute a twin‑prime pair and are printed.
List<Integer> list = new ArrayList<>();
for (int i = 2; i < 10000; i += 2) {
list.add(i);
}
get(list, 0);
for (int i = 0; i < list.size() - 1; i++) {
int a = list.get(i);
int b = list.get(i + 1);
if (b - a == 2) {
System.out.println("Twin prime: " + a + "\t" + b);
}
}Sorting examples for practice
Two classic elementary sorting algorithms are provided as additional exercises: insertion sort (implemented as a stable in‑place sort) and bubble sort.
public static void insertionSort(int[] data) {
for (int i = 0; i < data.length; i++) {
for (int j = i; j > 0; j--) {
if (data[j] < data[j - 1]) {
int tmp = data[j];
data[j] = data[j - 1];
data[j - 1] = tmp;
}
}
}
}
public static void bubbleSort(int[] data) {
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data.length - i - 1; j++) {
if (data[j] > data[j + 1]) {
int tmp = data[j];
data[j] = data[j + 1];
data[j + 1] = tmp;
}
}
}
}Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
