Program to output a subset of the composite numbers

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Aug 15 12:45:46 EDT 2018


On Wed, 15 Aug 2018 05:34:06 -0700, tomusatov wrote:

> I am not terribly familiar with Python, but am currently authoring an
> integer sequence for www.oeis.org and was wondering if anyone in the
> community could help me with authoring a Python program that outputs,
> "Composite numbers that are one less than a composite number."


Do you have a function to test for primality? For now, I'll assume you do.


def is_prime(n):
    # Returns True if n is prime, False otherwise.
    # implementation left as an exercise


# 0 (and 1) are neither prime nor composite; skip them.
# 2 and 3 are prime; start at the first composite, 4
i = 4
for j in range(5, 1001):
    if not is_prime(j):
        print(i)
    i = j


The above will stop at 999. To go forever, use this instead:



from itertools import count
i = 4
for j in count(5):
    if not is_prime(j):
        print(i)
    i = j



Alternatively, if you have a function which efficiently returns primes 
one at a time, you can do this:


n = 4  # start at the first composite
for p in primes(5):  # primes starting at 5
    print(list(range(n, p-1))
    n = p + 1



This ought to print out lists of composites, starting with:

[]
[]
[8, 9]
[]
[14, 15]


etc. Take care though: I have not tested this code.



-- 
Steven D'Aprano
"Ever since I learned about confirmation bias, I've been seeing
it everywhere." -- Jon Ronson




More information about the Python-list mailing list