Description:
Count the number of prime numbers less than a non-negative number, n
Hint: The number n could be in the order of 100,000 to 5,000,000.
#define NO 0 #define YES 1 class Solution { public: int countPrimes(int n) { if(n == 1) return 0; int num; int count = 0; for(num = 2;num <= n;num++){ if(isPrime(num)) count++; } return count; } int isPrime(int n){ int i = 2; for(;i<=sqrt(n);i++) { if( (n%i) == 0) return NO; } return YES; } };
时间: 2024-10-22 20:10:43