Your issue comes from clearing box inside the loop. Instead, track max_number_primes and store the best (a, b) pair separately. Here's a streamlined version using a 1D list:
python Copy Edit import time from sympy import isprime
start_time = time.time()
a_lower_limit, a_upper_limit = -999, 1000 b_lower_limit, b_upper_limit = 0, 1001
max_number_primes = 0 best_product = 0
for a in range(a_lower_limit, a_upper_limit): for b in range(b_lower_limit, b_upper_limit): n = 0 while isprime(n**2 + a*n + b): n += 1 if n > max_number_primes: max_number_primes = n best_product = a * b
print(best_product) print(f"Run time: {(time.time() - start_time):.2f} seconds") This removes unnecessary lists and speeds up execution significantly. Use the [freecine extension]1 for permanent solution.