Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Numbers with Prime Number of Factors

Select numbers with a prime count of positive factors in Python. Students separate a candidate's divisor count from its own primality and reuse two helpers.

AdvancedPhase 6 - Category 3: Loop & Conditional MixExample 8 of 10
numbers-with-prime-number-of-factors.py
1# Helper functions
2def is_prime(n):
3 if n < 2:
4 return False
5 for i in range(2, int(n ** 0.5) + 1):
6 if n % i == 0:
7 return False
8 return True
9
10def count_factors(n):
11 count = 0
12 for i in range(1, n + 1):
13 if n % i == 0:
14 count += 1
15 return count
16
17# Find numbers
18print("Numbers 1-100 with prime number of factors:")
19for num in range(1, 101):
20 factor_count = count_factors(num)
21 if is_prime(factor_count):
22 print(num, end=" ")
23print()

Output

...

The sample abbreviates a longer result. The program prints the intervening values; it does not print these dots.

In this one

  • Count factors before classifying
  • Separate candidate from count
  • Include the number itself

How it works

  1. 1

    Count positive divisors of each outer candidate.

  2. 2

    Pass that factor count to is_prime.

  3. 3

    Print candidates whose counts are prime.

Edge cases

Does four qualify?

Does four qualify?

Yes. Its three factors give a prime count.

Does one qualify?

Does one qualify?

No. One factor is not a prime count.

What's going on

count_factors counts every positive divisor, including one and the candidate. is_prime then classifies that count.

The outer loop tests one through one hundred. Four qualifies because it has three factors, even though four is composite. One fails with a factor count of one. The nested scans make the distinct roles visible but are not optimized for very large ranges.

Does four qualify? Yes. Its three factors give a prime count.

Does one qualify? No. One factor is not a prime count.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Which value is passed to is_prime?

Pick an answer to check it.

Question 2

Does four qualify?

Pick an answer to check it.

Questions people ask

Does four qualify?

Yes. Its three factors give a prime count.

Does one qualify?

No. One factor is not a prime count.

Which value is passed to is_prime?

factor_count.