Home > Back-end >  my code to count prime twins within a range of (2, n) only works with certain values of N
my code to count prime twins within a range of (2, n) only works with certain values of N

Time:09-18

challenge

A twin prime is a prime number that is either 2 less or 2 more than another prime number—for example, either member of the twin prime pair (41, 43). In other words, a twin prime is a prime that has a prime gap of two. Sometimes the term twin prime is used for a pair of twin primes; an alternative name for this is prime twin or prime pair. (from wiki https://en.wikipedia.org/wiki/Twin_prime)

Your mission, should you choose to accept it, is to write a function that counts the number of sets of twin primes from 1 to n.

If n is wrapped by twin primes (n-1 == prime && n 1 == prime) then that should also count even though n 1 is outside the range.

Ex n = 10

Twin Primes are (3,5) (5,7) so your function should return 2!

I am trying to complete this challenge, my code seems to work for some values of N but for some it returns answers too small, and when N = 2 it should return 3 (according to challenge tests).

So far I have tried fiddling with the count = system, so for example:

if prime_list[count]   2 or prime_list[count] - 2 in prime_list:
count  = 1

but changing this has not solved my issue yet

(I am new)

Here is my code

def prime_finder(n):
    primes = []
    for possibleprime in range(2, n   1):
        isprime = True
        for num in range(2, possibleprime):
            if possibleprime % num == 0:
                isprime = False
        if isprime:
            primes.append(possibleprime)
    return primes


def twin_prime(n):
    prime_list = prime_finder(n)
    count = 0
    for i in prime_list:
        if prime_list[count]   2 or prime_list[count] - 2 in prime_list:
            count  = 1
        elif prime_list[count]   2 and prime_list[count] - 2 in prime_list:
            count  = 2
    twin_count = count // 2
    return twin_count

CodePudding user response:

i is one of the primes, so you should be adding to i, not prime_list[count].

There's no need to add and subtract, because that will count each pair twice. Just add 2, check if that's a prime, and return that count, rather than dividing by 2.

def twin_prime(n):
    prime_list = prime_finder(n)
    count = 0
    for i in prime_list:
        if i   2 in prime_list:
            count  = 1
    return count
  • Related