1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Looking for proportion of prime numbers in a list, error in code (Python)

Discussão em 'Python' iniciado por Stack, Novembro 23, 2025.

  1. Stack

    Stack Membro Participativo

    I know my code doesn't work for this task, as it's too slow, but I also want to find what my error is, and I can't.

    The task is to find the point at which the proportion of primes in a list drops below a certain percentage (the diagonals in this spiral of numbers below)

    I generated primes up to a point, then compare the list of numbers to it, but the answer I get is much, much lower than the correct answer, and I don't know why. My answer was 631 (for below 10%), correct answer is 26000 something.

    As said, I know my approach doesn't work, so I'll redo that, but I also want to know why I'm getting the wrong answer anyway.

    Thanks for any help.

    [​IMG]

    len_limit = 6 # for generating primes. I've adjusted this limit based on how far I get up to
    limit = 10 ** len_limit
    primes2 = [True] * (limit + 1)
    primes2[0] = primes2[1] = False
    for i in range (2,int(limit ** 0.5) + 1):
    for n in range(2, int(limit / i) + 1):
    primes2 [i*n] = False
    primes = []
    for i in range(len(primes2)):
    if primes2 == True:
    primes.append(i)

    def make_square(side_length): # making all the numbers into a list
    a,b = 0,0
    nums = [1]
    square_size = side_length
    for n in range(2,square_size):
    nums.append(4 * n ** 2 - 10 * n + 7) # NE
    nums.append((2*n - 1) ** 2) # SE
    nums.append(4 * n ** 2 - 8 * n + 5) # NW
    nums.append(4 * n ** 2 - 6 * n + 3) # SW
    nums.sort()
    return nums

    def fraction_prime(side_length):
    nums = make_square(side_length)
    a,b = 0,0
    for num in nums:
    if num in primes:
    a += 1
    b += 1
    else:
    b += 1
    return (a/b)

    i = 3
    while True:
    i += 1
    fraction_prime(i)
    side_length = 2 * i - 3
    # print(fraction_prime(i),side_length,i) # optional, just to check that it was working
    if fraction_prime(i) <= 0.40: # not the number needed in the question, just to see if it works
    print(fraction_prime(i),side_length,i)
    if fraction_prime(i) < 0.40:
    break

    Continue reading...

Compartilhe esta Página