Reputation: 21
I'm doing a project Euler question (if you've done it, don't spoil it!) I've create a while loop in the following code. When I run the code, it doesn't give me an error message, but just doesn't give me an answer. I suspect that there is a problem with my while loop that makes it loop on infinitely.
import math
def euler(n):
m=[]
a=1
c=0
while c<=int(n):
a+=a
c=0
for x in range(1, int(math.sqrt(a))+1):
if n%x==0:
if n/x==x:
c+=1
else:
c+=2
print(a)
I don't know what's wrong with the loop. Could someone help me understand what is wrong and why?
Upvotes: 0
Views: 80
Reputation: 34046
The problem is the c=0
statement inside the while loop.
while c<=int(n):
a+=a
c=0 ## Problematic
for x in range(1, int(math.sqrt(a))+1):
if n%x==0:
if n/x==x:
c+=1
else:
c+=2
For every iteration c
is becoming 0 in the while loop, so it will always be less than n
. Hence the loop runs infinitely.
Upvotes: 1