题目描述
Description:
Count the number of prime numbers less than a non-negative number, n
题目出处: https://leetcode.com/problems/count-primes/题目分析
给定一个正数,找出小于该数的所有质数
代码
package com.larry.easy;
import java.util.Arrays;
/**
* 给定一个整数,找到小于该整数的所有质数
* @author admin
*
*/
public class CountPrimes {
private int countPrimes(int n) {
if(n < 2) return 0;
int s[] = new int[n+1];
for(int i = 0; i < n; i++)
s[i] = 0;
for(int i = 4; i < n; i = i + 2) s[i] = 1;
for(int i = 3; i*i < n; i = i + 2){//i*i是关键
if(s[i] == 1) continue;
for(int j = i; i*j < n; j = j + 2)//每个奇数与以后的奇数(包括自身)相乘
s[i*j] = 1;
}
//System.out.println(Arrays.toString(s));
int sum = 0;
for(int i = 2; i < n; i++)
if(s[i] == 0) sum++;
return sum;
}
public static void main(String[] args) {
System.out.println(new CountPrimes().countPrimes(24));
}
}<span style="color:#ff0000;">
</span>