- Factors of a number: all integers from 1 to n that divide n exactly (remainder 0). Check with
n % i == 0. Loop i from 1 to n (NOT 0 β avoid division by zero!). - Prime number: a number with exactly TWO factors (1 and itself). So count the factors; if count == 2, it's prime; otherwise not.
Letβs go! π
Part 1: What Are Factors?
π A factor of a number n is any integer that divides n exactly (remainder 0).
Example: Factors of 12
- 12 Γ· 1 = 12 remainder 0 β 1 is a factor
- 12 Γ· 2 = 6 remainder 0 β 2 is a factor
- 12 Γ· 3 = 4 remainder 0 β 3 is a factor
- 12 Γ· 4 = 3 remainder 0 β 4 is a factor
- 12 Γ· 5 = 2 remainder 2 β 5 is NOT a factor
- 12 Γ· 6 = 2 remainder 0 β 6 is a factor
- 7, 8, 9, 10, 11 don't divide 12 exactly
- 12 Γ· 12 = 1 remainder 0 β 12 is a factor
So factors of 12 are: 1, 2, 3, 4, 6, 12.
How to check in code: n % i == 0 means "i divides n exactly."
Demo: Factors of 12
n = 12
for i in range(1, n + 1):
if n % i == 0:
print(f" {i} is a factor (12 % {i} = 0)")
Part 2: Loop from 1 to n (NOT 0!)
π We must check i = 1, 2, 3, ..., n. So: for i in range(1, n+1):
β οΈ Do NOT use range(0, n+1). If i is 0, then n % 0 causes "division by zero" error! Always start from 1: range(1, n+1).
Part 3: Program β Print All Factors
Steps:
n = int(input("Enter a number: "))
for i in range(1, n + 1):
if n % i == 0:
print(i)
Demo: Factors of 12 (one line)
n = 12
factors = [i for i in range(1, n + 1) if n % i == 0]
print(" ", factors)
Part 4: What is a Prime Number?
π A prime number has exactly TWO factors: 1 and the number itself.
Examples:
- 11 β Factors: 1 and 11 only. So 11 is prime.
- 10 β Factors: 1, 2, 5, 10 (four factors). So 10 is not prime.
- 7 β Factors: 1 and 7 only. So 7 is prime.
So the rule: count the factors. If count == 2 β prime; otherwise not prime.
Part 5: Program β Prime Check
Steps:
n = int(input("Enter a number: "))
count = 0
for i in range(1, n + 1):
if n % i == 0:
count += 1
if count == 2:
print("Prime")
else:
print("Not prime")
Same loop as factors; we just count instead of printing. If count is 2, it's prime.
Demo: Prime check for 11 and 10
for n in [11, 10]:
count = 0
for i in range(1, n + 1):
if n % i == 0:
count += 1
print(f" {n}: {count} factors β {'Prime' if count == 2 else 'Not prime'}")
Part 6: Summary
β
Factors: for i in range(1, n+1): if n % i == 0: print(i) (Always start from 1 to avoid division by zero.)
β
Prime: Count factors. If count == 2 β prime; else β not prime. count = 0; for i in range(1, n+1): if n % i == 0: count += 1 if count == 2: print("Prime") else: print("Not prime")
Congratulations! You now understand Factors and Prime Number Check in Python! π
Key Takeaways:
- Use
n % i == 0to test if i is a factor - Loop from 1 to n (never 0)
- Prime = exactly 2 factors (1 and itself)
- Count factors or stop early when count > 2
Next Steps:
- Practice with user input
- Try printing only prime factors
- Optimize: loop only to sqrt(n) for faster prime check