pythonfactoring

Find all the divisors of a number using Python


I am trying to write a Python script that will find prime numbers. In the way that I am going about this, the script is going to take a number from a range, determine the factors, determine if the only two factors are 1 and itself, and return true if it's a prime number. I need help with my code to find the factors.

num = int(input("enter: "))

i = 1

while i < num:
  if num % i == 0:
    print(i)
    i += 1
  else:
    pass

The i is set to 1 because you can't divide by 0. However, the return starts to work, however, it only returns a couple of numbers, not the full list that I am hoping for. For example, you input 20, it returns only 1 and 2.


Solution

  • You're only incrementing i in the "is even" case. This'd fix it:

    num = int(input("enter: "))
    
    i = 1
    
    while i < num:
      if num % i == 0:
        print(i)
      i += 1
    

    However, it's better to use range() for iterating over a range of numbers:

    num = int(input("enter: "))
    for i in range(1, num):
      if num % i == 0:
        print(i)