0

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
  • 1
    Did you try to run this code with a debugger and see what happens to values: c, n, a, x? Also, what do you need m=[] for? I don't see it being used anywhere in the code? Commented Jan 11, 2019 at 7:51

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

But in the next lines of code, can't c change to become more than 0?
You're incrementing 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.
Why does it run on infinitely though? Even if I type a number like 5, the code runs infinitely. Why are the c+=1s and c+=2s not working?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.