HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Chen prime finder

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
primechenfinder

Problem

I've written a programme to find Chen primes. A Chen prime p is a prime number where (p + 2) is either also a prime number or has two prime factors.

I've got it working to the best of my knowledge: the first few values are correct.

def isprime(n):
  for m in range(2, int(n**0.5)+1):
     if not n%m:
        return False
  return True
m = 2
while True:
    if isprime(m):
        b = (m + 2)
        if isprime(b):
            print(m)
        for i in range(2, int((b)**0.5)+1):
            if b%i == 0:
                if isprime(i):
                    j = b/i
                    if isprime(j):
                        print(m)
    m = m + 1


The isprime(n) function definitely works; it's the while loop I'm more concerned with.

Solution

\$0\$ and \$1\$ corner cases

\$0\$ and \$1\$ are not primes, but your code returns:

>>> isprime(0), isprime(1)
(True, True)


is_chen_prime function and helper function

is_chen_prime should be a function of its own to improve re-usability.

A function to check if a number has two prime factors will make the code more similar to the mathematical description of the problem:

def is_chen_prime(n):
    return is_prime(n) and (is_prime(n + 2) or has_two_prime_factors(n + 2))

Code Snippets

>>> isprime(0), isprime(1)
(True, True)
def is_chen_prime(n):
    return is_prime(n) and (is_prime(n + 2) or has_two_prime_factors(n + 2))

Context

StackExchange Code Review Q#118811, answer score: 2

Revisions (0)

No revisions yet.