Question

This program is written to solve Project Euler Problem 27: Project Euler Problem 27

Here's the code:

   ab=[0,0]
b_list=[]
for x in range(2,1000):
    fact=1
    y=2
    while y*y<=x:
        if x==2:
            break
        if x%y==0:
            fact+=1
            break
        y+=1
    if fact==1:
        b_list.append(x)

number=0
max_=0
for a in range(-999,1000):
    for b in b_list:
        if a<=-b:
            continue
        n=0
        num_of_primes=0
        while True:
            number=((n*n)+(a*n)+b)
            n+=1
            print number
            if number>0:                
                factors=1
                div=2
                while div*div<=number:
                    if number==2:
                        break
                    if number%div==0:
                        factors+=1
                        break
                    div+=1
                if factors==1:
                    num_of_primes+=1
            else:
                break
        if max_<num_of_primes:
            max_=num_of_primes
            ab[0]=a
            ab[1]=b                
print ab[0]*ab[1]

But when I run this code, the code stops at a=-63 without giving any output. Can anybody suggest why that happens?

Was it helpful?

Solution

I think you could have thought about the problem a little bit more. Also, your code looks bit sluggish. Maybe it would help if you coded some functions instead of doing everything in one go. I see a lot of code repetition in there

Anyway, here's my two cents:

The program is probably stuck in the while True: cycle infinitely, as you only break out of the cycle when number <= 0. I haven't read your code with too much attention, but do you intend to break out of the while True: loop with the break statements that are inside the while div*div<=number: cycle? That is not possible. You would most probably need to have a variable to detect if you exit your loop prematurely and then break from the outer loop. Otherwise, maybe the else clause of python loops may help somehow (see Control Flow in Python).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top