⚡ TL;DR
Count primes below n in Dart with working code. Sieve of Eratosthenes approach with O(n log log n) time, plus complexity analysis and interview tips.
Count Primes (#204 — Medium): Given an integer n, return the number of prime numbers that are strictly less than n.
Problem Statement
Given an integer n, return the number of prime numbers that are strictly less than n.
Example:
Input: n = 10
Output: 4
Explanation: the primes below 10 are 2, 3, 5 and 7.Approach: Sieve of Eratosthenes
Time: O(n log log n) | Space: O(n)
Assume every number below n is prime, then walk the sieve from 2: each prime i knocks out its multiples i², i²+i, … — so every composite is crossed off exactly once by its smallest factor.
int countPrimes(int n) {
if (n < 3) {
return 0;
}
List<bool> sieve = List<bool>.filled(n, true);
sieve[0] = false;
sieve[1] = false;
int i = 2;
while (i * i < n) {
if (sieve[i]) {
for (int j = i * i; j < n; j += i) {
sieve[j] = false;
}
}
i++;
}
int count = 0;
for (final flag in sieve) {
if (flag) {
count++;
}
}
return count;
}
void main() {
print('Primes below 10: ${countPrimes(10)}');
}Approach: Trial Division
Time: O(n√n) | Space: O(1)
Test each candidate for primality by dividing by every d up to √num — no extra memory, and a clear demonstration of why the sieve wins as n grows.
bool isPrime(int num) {
if (num < 2) {
return false;
}
int d = 2;
while (d * d <= num) {
if (num % d == 0) {
return false;
}
d++;
}
return true;
}
int countPrimesTrial(int n) {
int count = 0;
for (int num = 2; num < n; num++) {
if (isPrime(num)) {
count++;
}
}
return count;
}
void main() {
print('Primes below 10: ${countPrimesTrial(10)}');
}Key Takeaways
- The sieve crosses off composites in bulk; trial division re-checks them one by one
- Starting the inner strike at i² is the classic sieve optimization — smaller multiples are already gone
- Only check divisors up to √num: any larger factor pairs with one below the square root
FAQ
What is the best approach to solve Count Primes in Dart?
The recommended approach is Sieve of Eratosthenes, which runs in O(n log log n) time with O(n) space. The full Dart implementation is shown above.
What is the time complexity of Count Primes in Dart?
Using Sieve of Eratosthenes, the time complexity is O(n log log n) and the space complexity is O(n); Trial Division runs in O(n√n) time with O(1) space.
Happy coding!

Written by Mihir Pipermitwala
Senior Full Stack Consultant & Mobile Engineering Specialist building user-focused applications in healthcare with Flutter, Dart and React Native. I write about what I actually build and test — every tutorial here comes from real project work.
More about Mihir →