Count Prime
https://leetcode.com/problems/count-primes/
A prime number is a number that is only divisible by 1 and itself
Version 1
According to the definition of prime number, we can create
a function isPrime
to test if a number n is a prime number:
|
|
Then, we can iterate through all the number between 1 to n for all the
prime numbers. O(n^2)
Version 2
Some of the step in the for-loop in the isPrime
is not necessary since
if n
is not a prime number, then there must be n = p x q
and p <= q
,
then p must be less than sqrt(n)
. We only need to test for p
to get
all the information if n
is a prime number.
|
|
isPrime(n)
is now O(sqrt(n))
, total complexity is O(n * sqrt(n))
Version 3
The idea is to build a table boolean[n]
, mark
all the non-prime numbers from 2 to n and the un-marked is prime numbers.
The reason it is faster is that it uses extra space for dynamic programming.