本文共 792 字,大约阅读时间需要 2 分钟。
Description:
Count the number of prime numbers less than a non-negative number, n采用筛选法,依次分别去掉2的倍数,3的倍数,5的倍数,……,最后剩下的即为素数。
//Rumtime:83msclass Solution { public: int countPrimes(int n) { int count = 0; bool *b = new bool[n]; b[2] = true; //2是偶数,但不能被筛掉,需要特殊考虑 for (int i = 3; i < n; i++) { if (i & 1) { b[i] = true; //奇数 } else { b[i] = false; } } for (int i = 2; i < n; i++) { if (b[i]) { count++; for (int j = 2; j * i < n; j++) { b[i * j] = false; } } } delete [] b; return count; }};
转载地址:http://cataa.baihongyu.com/