A factor (or divisor) of a number divides it with no remainder. The factors of 12 are 1, 2, 3, 4, 6 and 12.
The program
python
n = int(input("Enter a positive number: ")) factors = [] for i in range(1, n + 1): if n % i == 0: factors.append(i) print(f"Factors of {n}: {factors}") print(f"{n} has {len(factors)} factors")
Typed in this example: 36. Press Run to type your own.
output
Enter a positive number: 36 Factors of 36: [1, 2, 3, 4, 6, 9, 12, 18, 36] 36 has 9 factors
How it works
n % iis the remainder ofndivided byi. When it is 0,iis a factor.- The loop tests every number from 1 to
n, so the list comes out in order. - The program is for positive numbers. For 0 or a negative number the loop does not run, and the list is empty.
A number with exactly two factors (1 and itself) is prime. To split a number into its prime factors, see prime factors.
A faster way
Factors come in pairs: if i is a factor of n, then n // i is too. For 36 the pairs are 1 and 36, 2 and 18, 3 and 12, 4 and 9, and 6 and 6. So the loop only needs to go up to the square root of n:
python
import math def factors(n): small = [] large = [] for i in range(1, math.isqrt(n) + 1): if n % i == 0: small.append(i) if i != n // i: large.append(n // i) return small + large[::-1] print(factors(36)) print(factors(97)) print(len(factors(1_000_000)))
output
[1, 2, 3, 4, 6, 9, 12, 18, 36] [1, 97] 49
math.isqrt(n)is the whole-number square root:math.isqrt(36)is 6.if i != n // istops 6 from being added twice for 36.largeis filled from the biggest factor down, solarge[::-1]reverses it to keep the whole list in order.- For 1,000,000 the loop runs 1,000 times instead of 1,000,000. The perfect number page uses the same pairs idea.