欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Count Primes

程序员文章站 2022-03-13 12:09:17
...
Description:

Count the number of prime numbers less than a non-negative number, n.

给定一个整数,返回小于它的所有质数。我们借助一个布尔数组,来记录哪些数已经被标记为不为质数,每次循环的时候都从一个质数开始。最后只需要遍历一遍布尔数组中值为true的元素个数就可以了。代码如下:

public class Solution {
public int countPrimes(int n) {
boolean[] prime = new boolean[n];
Arrays.fill(prime, true);
int count = 0;
for(int i = 2; i < n; i++) {
if(prime[i]) {
for(int j = i * 2; j < n; j += i) {
prime[j] = false;
}
}
}
for(int i = 2; i < prime.length; i++) {
if(prime[i])
count ++;
}
return count;
}
}
相关标签: 质数