Hyun J
Hyun J

Reputation: 11

My code is infinitely looping and I'm not sure why

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

Answers (3)

smci
smci

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.

  • but even that is roundabout. Your while-loop that starts x at 2, increments x by +1, and stops when x > number, is really just a for-loop in disguise: for x in range(2, number+1): ...
  • But you can show we strictly only need to do:
    • for x in range(2, ceil(sqrt(number)+1): ... where we use math.sqrt, math.ceil
  • ...really you need to store the quotient between iterations, and when it gets to 1 you know you can terminate early; you've found all the divisors of number

Upvotes: 0

Guinther Kovalski
Guinther Kovalski

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

BrokenBenchmark
BrokenBenchmark

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

Related Questions