⚡ TL;DR
Count primes below n in Go 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.
package main
import "fmt"
func countPrimes(n int) int {
if n < 3 {
return 0
}
sieve := make([]bool, n)
for i := 2; i < n; i++ {
sieve[i] = true
}
for i := 2; i*i < n; i++ {
if sieve[i] {
for j := i * i; j < n; j += i {
sieve[j] = false
}
}
}
count := 0
for _, flag := range sieve {
if flag {
count++
}
}
return count
}
func main() {
fmt.Println("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.
package main
import "fmt"
func isPrime(num int) bool {
if num < 2 {
return false
}
for d := 2; d*d <= num; d++ {
if num%d == 0 {
return false
}
}
return true
}
func countPrimesTrial(n int) int {
count := 0
for num := 2; num < n; num++ {
if isPrime(num) {
count++
}
}
return count
}
func main() {
fmt.Println("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 Go?
The recommended approach is Sieve of Eratosthenes, which runs in O(n log log n) time with O(n) space. The full Go implementation is shown above.
What is the time complexity of Count Primes in Go?
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 →