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?
1 Answer 1
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.
3 Comments
c at most by 2 for each factor of n, and you'd have to be lucky for that to add up to n or more.
m=[]for? I don't see it being used anywhere in the code?