Reputation: 11
My code is just a simple prime factorization calculator. I'm not sure why it's infinitely looping. I'm pretty new to Python and not entirely sure on how the while loop works.
def print_prime_factors(number):
x = 2
while x < number:
if number % x == 0:
y = number/x
print(str(x)+",")
y = number
if x > y:
break
x = x + 1
print_prime_factors(100)
# Should print 2,2,5,5
# DO NOT DELETE THIS COMMENT```
Upvotes: 1
Views: 148
Reputation: 33938
(1) The first bug is, as others have said, that your line x = x + 1
that increments candidate x should be unindented one level, so it's under the while-loop.
(2) But you also have a bug with what you're doing with quotient y, it's mystifying.
When you identify that x is a factor of number
, just print x. You compute the quotient y = number/x
, silently throw it away, then assign y = number
, which again gets thrown away. You could have just directly tested if x > number: ... break
.
number
, is really just a for-loop in disguise: for x in range(2, number+1): ...
for x in range(2, ceil(sqrt(number)+1): ...
where we use math.sqrt
, math.ceil
number
Upvotes: 0
Reputation: 1919
after the first iteration x changes and the if statements is never true again, which makes x never changes again. Seens to be just indentation problem.
Upvotes: 1
Reputation: 19242
Your code has an indentation error.
This line:
x = x + 1
should be shifted over one indent. You're only incrementing x
whenever it is a factor of the number, which means that the program will enter an infinite loop by repeatedly checking whether number
is divisible by a non-factor of number.
Upvotes: 4