"204-count Primes (statistic prime numbers)"
" leetcode-interview algorithm classic-java Implementation" "All topic Directory Index"
code Download "Https://github.com/Wang-Jun-Chao"
Original title
Description:
Count the number of prime numbers less than a non-negative number, N.
The main effect of the topic
Counts the number of primes less than the nonnegative integer n.
ideas for solving problems
Use See Eratosthenes-color sieve method.
Code Implementation
Algorithm implementation class
public class Solution {public
int countprimes (int n) {
if (n <= 1) {return
0;
}
Default all element values are set to False
boolean[] Notprime = new Boolean[n];
Notprime[0] = true;
Notprime[1] = true;
for (int i = 2; I * i < n; i++) {
//If I is a prime number, I set the multiple of I to a non prime number
//If I is a composite number, then it must have been set to true because it is processed from 2
if (!not Prime[i]) {for
(int j = 2 * i; j < n; j + = i) {
notprime[j] = True
;
}} Count the number of prime numbers
int result = 0;
For (Boolean b:notprime) {
if (!b) {
result++
}}
}
return result;
}
Evaluation Results
Click on the picture, the mouse does not release, drag a position, released in a new window to view the full picture.
Special Description Welcome reprint please indicate the source "http://blog.csdn.net/derrantcm/article/ details/48021413 "