Reputation: 667
I wrote a function to tell if certain number is a perfect number: a number is a perfect number if the summation of all it's factor equals to itself.
The function goes like:
def is_perfect(n):
l = [1]
temp = n
while temp != 1:
for i in range(2,n):
if temp % i ==0:
l.append(i)
temp = int(temp / i)
break
if sum(l)==n:
return True
else:
return False
I want it to return boolean value according to the input. Then I want to use a for loop to find out all the perfect number with my function above, but it seems there's a infinite loop. Where am I wrong?
a=[]
for x in range(1,1001):
if is_perfect(x):
a.append(x)
print([x for x in a])
Upvotes: 0
Views: 569
Reputation: 977
Your function goes into an infinite loop when a prime number is passed in. This is because your while loop condition depends on temp
being modified upon every iteration, but if n
is prime this never happens. The reason why is in this line:
if temp % i == 0:
When n
is prime the code in your if-statement block gets passed over completely, including the line that reassigns the temp
variable.
Upvotes: 1