Hints
- We can immediately cut the total iterations half by dividing only up to n / 2.
1
is not a prime!- All three hints in https://leetcode.com/problems/count-primes/ especially the third one
Attentions
- When adding index in the prime linkedlist, pay attention to the new element and the index, which should be equal to current
primeLL.size()
- For
countPrimesBySieveOfEratosthenes
method, we set the prime[i] to represent number i, instead of prime[i - 1]. As long as the start index is not 0, it is fine.
Optimization
- The increase of the for loop can avoid multiply
for (int j = 1; j*i < n; j++) {
prime[j*i] = true;
}
can be optimized to add i instead of multiply
for (int j = i; j < n; j = j + i)
prime[j] = true;
}