The easiest way is through this piece of logic: while a number can be prime and greater than 1
, try dividing it by prime numbers greater than its square root. For example, say we have 6
-- it's square root is ~2.449
. So we try to divide it by 3
, the next greater prime number, but we realize it is divisible and thus not prime. We'll expand on the logic for this shortly!

1for i in range(2, n+1):
2 isPrime = True
3 for j in range(2, int(math.sqrt(i))+1):
4 if i % j == 0:
5 isPrime = False
6 break
7 if isPrime:
8 res += i
Complexity of Final Solution
Let n
be the input number. We fill an array of size n
to keep track of potential prime candidates for O(n)
space complexity, and our while loop that updates our array performs roughly log n
work over n
iterations for O(n log n)
time complexity.