标签:tor bsp number str ash targe https prime summary
Problem:
Count the number of prime numbers less than a non-negative number, n.
Summary:
判断小于某非负数n的质数个数。
Solution:
用所谓的“刷质数表”的方式先用HashTable记录小于n的所有数是质数还是合数,再逐一数出。
看了题目中的Hint才知道这种方法有一个更加高大上的名字Sieve of Eratosthenes
即在每判断一个数为质数时,将它的bei‘shu倍数均计为合数。
1 class Solution { 2 public: 3 int countPrimes(int n) { 4 if (n == 0 || n == 1) { 5 return 0; 6 } 7 8 vector<int> prime(n, 0); 9 10 prime[0] = prime[1] = 1; 11 for (long long i = 2; i < n; i++) { 12 if (!prime[i]) { 13 for (long long j = i * i; j < n; j += i) { 14 prime[j] = 1; 15 } 16 } 17 } 18 19 int cnt = 0; 20 for (int i = 0; i < n; i++) { 21 if (!prime[i]) { 22 cnt++; 23 } 24 } 25 26 return cnt; 27 } 28 };
标签:tor bsp number str ash targe https prime summary
原文地址:http://www.cnblogs.com/VickyWang/p/6247512.html