204. Count Primes
来源:互联网 发布:无法登录战网检查网络 编辑:程序博客网 时间:2024/05/22 01:41
Description:
Count the number of prime numbers less than a non-negative number, n.
计算比N小的所有质数的个数
这道题花了好多时间,数学真实博大精深 ·.·
- 懵懂无知的我最开始是知道暴力求解是行不通的,然后发现第一种解法:把要除的所有比N小的数,变成了sqrt(n),直接少了一半,然后感慨了一番,结果。。。。这尽然是最最基础的解法,并且LEETCODE中还超时!!
#include <iostream>#include <math.h>using namespace std;bool prime (int n){ int s=sqrt(n); for(int i=2; i<=s; i++) { if(n%i==0) return false; return true; }}int main(){ int n; while(true) { cin>>n; cout<<prime(n)<<endl; }}
- 然后继续寻找,有很 多种解法,这里只写我理解的一种:
- 配合这个神图
解法都在图中:
首先计算2的倍数并标记,然后计算3……一直到sqrt(n),最后输出未被标记的数,就是质数了。
我用的vector<int>
来保存数组,0代表未标记,1代表标记,最开始想的用vector<bool>
来保存,没想到这是个Bug ,长知识了
还要注意的一点是初始化数组后,要减去第一位0和第二位1这俩位数
class Solution {public: int countPrimes(int n) { if(n<2) return 0; vector<int> v(n,0); int k=n-2; for(int i=2; i<sqrt(n); i++) { for(int j=i; i*j<n; j++) { if(v[i*j]==0) { k--; //计算一共有多少质数 v[i*j]=1; //标记不能不写,不然会有重复 } } } return k; }};
0 0
- 204. Count Primes
- 【LeetCode】204.Count Primes
- [leetcode] 204.Count Primes
- LeetCode 204. Count Primes
- Leetcode 204. Count Primes
- 204. Count Primes
- 204. Count Primes
- [LeetCode]204. Count Primes
- 204. Count Primes LeetCode
- 204. Count Primes
- 204. Count Primes
- 204. Count Primes
- 204. Count Primes
- LeetCode *** 204. Count Primes
- 204. Count Primes
- LeetCode 204. Count Primes
- leetcode-204. Count Primes
- 204. Count Primes
- Android面试题——ListView(二)
- Cocos2dx在Android Studio中报java.lang.UnsatisfiedLinkError的解决办法
- 迟来的4月小结
- 2016年5月1日
- 远程连接mysql/mariaDB数据库时出现1045错误
- 204. Count Primes
- 关于居中
- CM和CMTS的概念和信令交互过程
- tableView中的cell复制粘贴操作
- bzoj 2588: Spoj 10628. Count on a tree(树上主席树)
- IOS总体学习思路(16.5.1)
- 是时候贴上校园漫游的成品了【记录】
- 如何复制cmd命令行文字
- ActiveMQ小记(一):监控