Skip to main content

Below is a piece of code for problem 35problem 35 which I'm fairly certain works correctly so far with numbers under 10000 however when I set it to 1 million it takes way too long to run. I still havent got an answer yet and it's been running for about 15 mins....

Below is a piece of code for problem 35 which I'm fairly certain works correctly so far with numbers under 10000 however when I set it to 1 million it takes way too long to run. I still havent got an answer yet and it's been running for about 15 mins....

Below is a piece of code for problem 35 which I'm fairly certain works correctly so far with numbers under 10000 however when I set it to 1 million it takes way too long to run. I still havent got an answer yet and it's been running for about 15 mins....

Tweeted twitter.com/StackCodeReview/status/879029308152578048
edited tags; edited title
Link
200_success
  • 145.7k
  • 22
  • 191
  • 481

finding Finding circular primes efficiency

Source Link

finding circular primes efficiency

I'm coding for a project euler question and every now and then, the question will demand a program that is efficient even when doing brute force. Which I struggle with.

Below is a piece of code for problem 35 which I'm fairly certain works correctly so far with numbers under 10000 however when I set it to 1 million it takes way too long to run. I still havent got an answer yet and it's been running for about 15 mins....

If anyone could give me general tips on efficiency that would be awesome!

def rwh_primes(n):
    sieve = [True] * n
    for i in range(3,int(n**0.5)+1,2):
        if sieve[i]:
            sieve[i*i::2*i]=[False]*int((n-i*i-1)/(2*i)+1)
    return [2] + [i for i in range(3,n,2) if sieve[i]]


def is_prime(n):
    for i in range(3, n):
        if n % i == 0:
            return False
    return True


def f7(seq):
    seen = set()
    seen_add = seen.add
    return [x for x in seq if not (x in seen or seen_add(x))]

primes = rwh_primes(1000000)
lisp = []
working = []
count = 0
counter = 0

for x in primes:
    z = 1
    y = (len(str(x)) + 1)

    if len(str(x)) == 2:
        thingy = list(str(x))
        number = int(thingy[1] + thingy[0])
        if is_prime(number) == True:
            lisp.append(x)

    elif len(str(x)) < 2:
        lisp.append(x)

    else:
        while count < len(sorted(str(x))) - 1:
            num = list((str(x) + str(x)))
            new = num[z:y]
            newest = ''.join(new)
            verynew = int(newest)
            working.append(verynew)
            count += 1
            z += 1
            y += 1

            if count == len(sorted(str(x))) - 1:
                for a in working:
                    if is_prime(a) == True:
                        counter += 1
                        if counter == len(working):
                            lisp.append(x)
                            lisp = f7(lisp)
        count = 0
        counter = 0
        working = []

print(len(lisp))