I'm trying to solve this Project Euler task which 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.
I know my approach doesn't work because it's too slow, so I'll redo that, but I also want to know why I'm getting the wrong answer anyway.
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[i] == 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
