Factors of a Number in Python: For Loop and Faster Methods

To find the factors of a number in Python, check which positive integers divide it with no remainder. For example, the factors of 12 are 1, 2, 3, 4, 6, 12. The % operator checks the remainder: n % i == 0 means i is a factor of n.

Start with this original for-loop example for 25.

Interactive Companion Jupyter Notebook

Run the Python examples, compare expected outputs, modify the code, and complete guided exercises.

View on GitHub Open in Google Colab
On this page — Show page sections (jump to a topic) — Hide page sections
n=25 # change this value 
for i in range (1,n+1):
  if(n%i==0):
    print(i,end=', ')

Output:

1, 5, 25, 

For 25, the factors are 1, 5 and 25. The trailing comma comes from print(i, end=', '); a later example shows how to format the output without it.

What are factors?

A factor (or divisor) is a whole number that divides another whole number exactly. For positive integers, both 1 and the number itself are factors. We focus on positive factors here; for negative integers, the same positive factors apply to the absolute value.

n = 12
for i in range(1, n + 1):
    if n % i == 0:
        print(i, end=" ")

Output:

1 2 3 4 6 12 

Here the condition is true for 1, 2, 3, 4, 6 and 12. For a detailed explanation of the Python if statement, follow the related tutorial.

Understand the for loop and remainder operator

The loop checks 1 through n. The range(1, n + 1) expression includes n because the end of a Python range is excluded. When n % i is zero, i divides n evenly.

ExpressionMeaningFor n = 12
range(1, n + 1)Test each positive integer up to n1 through 12
n % iRemainder after n is divided by i12 % 5 is 2
n % i == 0True when i is a factor12 % 4 == 0
print(i)Display a matching factor1, 2, 3, 4, 6, 12
n = 12
for i in (3, 5, 6):
    print(f"{n} % {i} = {n % i}; factor: {n % i == 0}")

Output:

12 % 3 = 0; factor: True
12 % 5 = 2; factor: False
12 % 6 = 0; factor: True

Find factors of a number entered by the user

The original interactive example calls int() to convert the text returned by input() into an integer. Change the number at the prompt when you run this in a terminal or Colab.

n=int(input("Enter a number : "))
#n=25
for i in range (1,n+1):
  if(n%i==0):
    print(i,end=', ')

Output:

Enter a number : 1, 2, 3, 4, 6, 8, 12, 24, 

The sample run supplies 24 at the prompt. int() raises ValueError for text such as hello. See the Python data types tutorial.

Show factors without a trailing comma

Instead of printing inside the loop, collect the divisors and use join() to produce a clean comma-separated result. The list comprehension uses the same factor test as the first example.

n = 25
factors = [i for i in range(1, n + 1) if n % i == 0]
print(", ".join(str(i) for i in factors))

Output:

1, 5, 25

You can also retain the Python list, for example [1, 5, 25], if you want to count or reuse the factors.

Check only up to half the number

The original tutorial reduces the search to half of n and then prints n itself. For every integer n > 1, every positive proper factor is at most n // 2. The number itself is added separately.

n=125
for i in range (1,int(n/2)+1):
  if(n%i==0):
    print(i,end=', ')
print(n)

Output:

1, 5, 25, 125

This preserves the original 125 demonstration. For positive integers, n // 2 is preferable to int(n / 2) because it avoids floating-point conversion.

n = 125
factors = [i for i in range(1, n // 2 + 1) if n % i == 0]
factors.append(n)
print(factors)

Output:

[1, 5, 25, 125]

This returns the same four factors without mixing numbers and display punctuation. The full-range method is often simpler to learn; the next method is substantially faster for large integers.

Faster method: find factor pairs up to the square root

If i divides n, then n // i is its paired factor. Checking only through math.isqrt(n) therefore finds both factors while making far fewer checks. This standard-library function gives the exact integer square root without floating-point rounding. Python 3.8 or newer is required for math.isqrt().

from math import isqrt
n = 36
factors = set()
for i in range(1, isqrt(n) + 1):
    if n % i == 0:
        factors.add(i)
        factors.add(n // i)
print(sorted(factors))

Output:

[1, 2, 3, 4, 6, 9, 12, 18, 36]

For the perfect square 36, 6 is paired with itself. The set prevents it from appearing twice; sorted() returns the factors in ascending order.

Create a reusable function to find factors

For repeated tasks, put the square-root approach into a function. This implementation returns a sorted list of positive factors and rejects zero, which does not have a finite set of positive divisors.

from math import isqrt

def positive_factors(n):
    if n == 0:
        raise ValueError("Zero has infinitely many positive divisors")
    n = abs(n)
    found = set()
    for i in range(1, isqrt(n) + 1):
        if n % i == 0:
            found.add(i)
            found.add(n // i)
    return sorted(found)

print(positive_factors(28))
print(positive_factors(125))

Output:

[1, 2, 4, 7, 14, 28]
[1, 5, 25, 125]

Use positive_factors(12), positive_factors(125) or another nonzero integer. The function returns data, so it can be used for prime checks and calculations.

Factors of 1, negative numbers and zero

1 has one positive factor: itself. A negative integer has the same positive factors as its absolute value, plus the negative versions of those factors if signed factors are needed. Zero is divisible by every nonzero integer, so it cannot be represented by a finite list of all factors.

from math import isqrt

def positive_factors(n):
    if n == 0:
        raise ValueError("Zero has infinitely many positive divisors")
    n = abs(n)
    result = set()
    for i in range(1, isqrt(n) + 1):
        if n % i == 0:
            result.update((i, n // i))
    return sorted(result)

print("1:", positive_factors(1))
print("-12:", positive_factors(-12))
try:
    print(positive_factors(0))
except ValueError as error:
    print("0:", error)

Output:

1: [1]
-12: [1, 2, 3, 4, 6, 12]
0: Zero has infinitely many positive divisors

Display factor pairs

The pairs (1, 36), (2, 18), (3, 12), (4, 9) and (6, 6) explain why the square-root approach works. Printing both halves makes the relationship visible.

from math import isqrt
n = 36
for i in range(1, isqrt(n) + 1):
    if n % i == 0:
        print(i, "x", n // i, "=", n)

Output:

1 x 36 = 36
2 x 18 = 36
3 x 12 = 36
4 x 9 = 36
6 x 6 = 36

Count the factors and calculate their sum

Once the factors are stored in a list, len() counts them and sum() adds them. This helps with number-property exercises such as perfect numbers.

n = 28
factors = [i for i in range(1, n + 1) if n % i == 0]
print("Factors:", factors)
print("Count:", len(factors))
print("Sum of proper factors:", sum(factors[:-1]))
print("Perfect number:", sum(factors[:-1]) == n)

Output:

Factors: [1, 2, 4, 7, 14, 28]
Count: 6
Sum of proper factors: 28
Perfect number: True

Use factors to identify a prime number

A positive integer greater than one is prime if its only positive factors are 1 and itself. The related Python prime numbers tutorial covers additional prime-number methods.

for n in (1, 2, 9, 13, 29):
    factors = [i for i in range(1, n + 1) if n % i == 0]
    is_prime = n > 1 and len(factors) == 2
    print(n, "prime:", is_prime)

Output:

1 prime: False
2 prime: True
9 prime: False
13 prime: True
29 prime: True

Compare the number of divisor checks

For a large positive n, the basic search makes n checks, the half-range search about n/2 checks, and the square-root approach approximately √n checks. The difference grows quickly for larger values.

from math import isqrt
for n in (25, 125, 10000, 1000000):
    print(f"n={n}: full={n}, half={n // 2}, sqrt={isqrt(n)}")

Output:

n=25: full=25, half=12, sqrt=5
n=125: full=125, half=62, sqrt=11
n=10000: full=10000, half=5000, sqrt=100
n=1000000: full=1000000, half=500000, sqrt=1000

Handle invalid input safely

An input prompt accepts text. Convert with int() inside try/except, reject zero, and use abs() for negative integers. Avoid silently converting decimal strings such as 3.8 to 3; factors are discussed here for integers.

from math import isqrt

def positive_factors(n):
    if n == 0:
        raise ValueError("Enter a nonzero integer")
    n = abs(n)
    factors = set()
    for i in range(1, isqrt(n) + 1):
        if n % i == 0:
            factors.update((i, n // i))
    return sorted(factors)

for text in ("24", "-10", "0", "hello", "3.8"):
    try:
        number = int(text)
        print(text, "->", positive_factors(number))
    except ValueError as error:
        print(text, "->", error)

Output:

24 -> [1, 2, 3, 4, 6, 8, 12, 24]
-10 -> [1, 2, 5, 10]
0 -> Enter a nonzero integer
hello -> invalid literal for int() with base 10: 'hello'
3.8 -> invalid literal for int() with base 10: '3.8'

Watch the original factors video tutorial

This video accompanies the original Plus2Net explanation of factors and remainder-based loops. The code examples above can be run independently of the video.

Common mistakes and troubleshooting

  • Nothing prints for a negative input: range(1, n + 1) is empty when n < 1; use abs(n) if you need positive factors.
  • Input is not an integer: int(input(...)) raises ValueError for text and decimal strings; validate the input first.
  • A trailing comma appears: end=", " prints a separator after the last factor; collect values and use join().
  • Zero is handled incorrectly: avoid treating 0 as having a finite divisor list.
  • Square root appears twice: if a number is a perfect square, its central factor is paired with itself; use a set or explicitly test for duplicates.
  • Precision issues on large integers: replace int(n / 2) with n // 2 and use math.isqrt(n) for integer square roots.
  • The range() endpoint is skipped: write range(1, n + 1) when testing through n.
  • Mixing up factors and prime factors: factors include composite divisors; prime factors are prime numbers that divide the original number.

Practice exercises

The Google Colab notebook includes executable challenges with assertions. Before opening the solutions, try:

  • Print all positive factors of 48 without a trailing comma.
  • Find the factors of 97. Is the number prime?
  • Use factor pairs to list the factors of 144, ensuring 12 appears only once.
  • Compare factors of 18 and 24 and identify the common factors.
  • Count the factors of 360 using math.isqrt().
  • Handle inputs 1, -36, and 0 with meaningful results.

Frequently asked questions

How do I find the factors of a number in Python?

Loop through candidate integers and keep the values where n % i == 0. For large numbers, use math.isqrt(n) and record each matching divisor together with n // i.

What are the factors of 12?

The positive factors are 1, 2, 3, 4, 6, 12. Each divides 12 with remainder zero.

Can I find factors without checking every number?

Yes. Check candidates up to the integer square root and collect both numbers in each factor pair. This generally makes far fewer checks than testing every integer from 1 through n.

What are the factors of 1 and 0?

1 has one positive factor: 1. Every positive integer divides zero, so zero has infinitely many positive factors and needs special handling in a factor-listing program.

Does this work for negative numbers?

Yes, when you explicitly decide what you want to return. To find positive factors of a negative integer, take its absolute value with abs(n).

What is the difference between factors and prime factors?

The factors of 12 are 1, 2, 3, 4, 6, 12, while its distinct prime factors are 2 and 3. See the prime numbers examples.

Do I need to install a Python library to practice?

No. The exercises use built-in Python features and the standard-library math module. For math.isqrt(), use Python 3.8 or newer.

Podcast on Python Basics

Back to top ↑




Subscribe to our YouTube Channel here



plus2net.com




Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer