Leetcode:204
编写一个程序判断给定的数是否为丑数。丑数就是只包含质因数 2, 3, 5 的正整数。
统计所有小于非负整数 n 的质数的数量。
示例:
输入: 10
输出: 4
解释: 小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。
1class Solution {
2public:
3 int countPrimes(int n) {
4 if(n<=1)
5 {
6 return 0;
7 }
8 int res = 0;
9 int val = (int)sqrt(n);
10 bool flag[n] = {0};
11 for(int i = 2;i<=val;i++){ //find the prime between 2 and √n
12 if(flag[i]==false){
13 for(int j = i*i;j<n;j+=i){
14 if(flag[j]==false)
15 {
16 res++; //Recording non-prime numbers,4,6,8,10,12,9
17 }
18 flag[j] = true; //set the flag
19 }
20 }
21 }
22 return n-res-2;
23 }
24};