Fundamentals 4 min read

How to Find Twin Primes with a Simple Recursive Sieve in Python and Java

This article explains a straightforward recursive sieve method for generating prime numbers, compares Java's in‑loop deletions with Python's deferred removal, provides full source code, and shows how to identify twin prime pairs while noting Python's recursion depth limitation.

FunTester
FunTester
FunTester
How to Find Twin Primes with a Simple Recursive Sieve in Python and Java

After reading the book *The Loneliness of Prime Numbers*, the author wanted to explore twin prime distribution and implemented a simple algorithm to generate primes and detect twin prime pairs.

The algorithm creates a list of integers starting from 2, then iteratively removes any number divisible by the current base number, effectively implementing a sieve. In Java, elements can be removed from the list during iteration by adjusting the loop index (i--) to avoid index errors; Python does not support in‑loop deletions, so elements are collected and removed after the traversal.

#!/usr/bin/python3

class Test():
    def __init__(self):
        print("fan")
    def get(self, lst, st):
        n = lst[st]
        a = []
        for i in range(st+1, len(lst)):
            if lst[i] % n == 0:
                a.append(lst[i])
        for x in a:
            lst.remove(x)
        if len(lst) > st+1:
            self.get(lst, st+1)

if __name__ == "__main__":
    test = Test()
    lst = [i for i in range(2, 5000)]
    test.get(lst, 0)
    for i in range(len(lst)-1):
        a = lst[i]
        b = lst[i+1]
        if b - a == 2:
            print("Twin primes: " + str(a) + "----" + str(b))

The program then scans the resulting prime list for consecutive primes whose difference is exactly 2 and prints each twin prime pair.

Note: Python limits recursion depth to prevent memory overflow, so attempting to process numbers up to 10,000 may raise a RecursionError: maximum recursion depth exceeded in comparison . Increasing the recursion limit or switching to an iterative approach is required for larger ranges.
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaPythonPrime NumbersRecursive AlgorithmTwin Primes
FunTester
Written by

FunTester

10k followers, 1k articles | completely useless

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.