Python Program to Find Factors of a Number
for i in range(1, n+1): and check if n % i == 0 to collect all factors.Examples
How to Think About It
Algorithm
Code
n = int(input('Enter a number: ')) factors = [] for i in range(1, n + 1): if n % i == 0: factors.append(i) print('Factors of', n, 'are:', *factors)
Dry Run
Let's trace the number 6 through the code to find its factors.
Input
n = 6
Initialize factors list
factors = []
Loop i from 1 to 6
Check each i if divides 6 evenly
Check i=1
6 % 1 == 0, add 1 to factors
Check i=2
6 % 2 == 0, add 2 to factors
Check i=3
6 % 3 == 0, add 3 to factors
Check i=4
6 % 4 != 0, skip
Check i=5
6 % 5 != 0, skip
Check i=6
6 % 6 == 0, add 6 to factors
Print factors
Factors of 6 are: 1 2 3 6
| i | n % i == 0? | Action | Factors List |
|---|---|---|---|
| 1 | True | Add 1 | [1] |
| 2 | True | Add 2 | [1, 2] |
| 3 | True | Add 3 | [1, 2, 3] |
| 4 | False | Skip | [1, 2, 3] |
| 5 | False | Skip | [1, 2, 3] |
| 6 | True | Add 6 | [1, 2, 3, 6] |
Why This Works
Step 1: Loop through numbers
We check every number from 1 to n because factors must be within this range.
Step 2: Check divisibility
Using n % i == 0 tells us if i divides n without remainder, meaning i is a factor.
Step 3: Collect factors
We add all such i values to a list to show all factors at the end.
Alternative Approaches
import math n = int(input('Enter a number: ')) factors = [] for i in range(1, int(math.sqrt(n)) + 1): if n % i == 0: factors.append(i) if i != n // i: factors.append(n // i) factors.sort() print('Factors of', n, 'are:', *factors)
n = int(input('Enter a number: ')) factors = [i for i in range(1, n + 1) if n % i == 0] print('Factors of', n, 'are:', *factors)
Complexity: O(n) time, O(n) space
Time Complexity
The program checks every number from 1 to n, so it runs in linear time O(n).
Space Complexity
It stores all factors found in a list, which in the worst case can be up to O(n) if the number is 1.
Which Approach is Fastest?
Checking up to the square root reduces time to O(√n), making it faster for large numbers compared to checking all up to n.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Check all up to n | O(n) | O(n) | Small numbers, simplicity |
| Check up to sqrt(n) | O(√n) | O(n) | Large numbers, better performance |
| List comprehension | O(n) | O(n) | Concise code, readability |