求primes的算法
2015-06-12 20:25
260 查看
1、利用定义
质数:一个大于1的自然数,除了1和它本身外,不能被其他自然数整除。
int primeDef(int x){ int count = 0; for(int key = 2; key <= x; key++){ int i = 2; for(i = 2; i < key; i++) if( key%i == 0 ) //若小于key的值能整除key,跳出循环,key不是质数 break; if( i == key ) //若i完成整个循环,key是质数 count++; } return count; } static void test(void){ int n = primeDef(100); //calcu the num of primes less than 100 cout<<n<<endl; }
2、根据定理
定理:一个合数的最小质因数必小于其开平方根,反之则为质数。
int primeLemma(int x){ int count = x-1; //initialize [2,x] as primes for(int key = 2; key <= x; key++){ int min_factor = (int)sqrt(key); int i = 2; for(i = 2; i <= min_factor; i++) if( key%i == 0 ){ //if can be divided, then count-- count--; break; } } return count; }
3、优化算法
筛选法求质数:
创建一个所求范围内质数真值数组偶数(2的倍数)全为false,奇数全为true
由最小质数开始筛选,其倍数必不为质数
int primeOpt(int x){ bool isPrime[x+1]; for(int i = 0; i < x-1; i+=2){ isPrime[i] = false; isPrime[i+1] = true; } int n = sqrt(x); int count = 0; for(int key = 2; key <= n; key++){ //n为x可能的最小质因数 int i = 2*key; for(i = 2*key; i <= x; i+= key){ if( isPrime[key] && isPrime[i] ) //若key为质数,则其小于x的倍数均为合数,因为有了key为其质因数 isPrime[i] = false; } } for(int i = 0; i < x+1; i++){ if( isPrime[i] == true ) count++; } return count; }
运行时间比较:
static void test(void){ clock_t t1,t2,t3; int n = 100000; t1 = clock(); int n1 = primeDef(n); t1 = clock() - t1; t2 = clock(); int n2 = primeLemma(n); t2 = clock() - t2; t3 = clock(); int n3 = primeOpt(n); t3 = clock() - t3; cout<<"nums:"<<n1<<" times: "<<t1<<" clicks"<<endl; cout<<"nums:"<<n2<<" times: "<<t2<<" clicks"<<endl; cout<<"nums:"<<n3<<" times: "<<t3<<" clicks"<<endl; }
输出:
nums:9592 times: 1555 clicks
nums:9592 times: 11 clicks
nums:9592 times: 2 clicks
thk
相关文章推荐
- hdu - 1689 Just a Hook (线段树区间更新)
- songtzu的创业产品的经历
- uva580(数学题)
- alsa和oss声音系统比较
- [安卓]手机管家(四)自定义属性
- 编写算法,对给定的字符串str,返回其最长重复子串及其下标位置
- Android—Activity的四种启动模式
- linux命令10--file
- Qt4学习(3)——用定时器循环播放图片
- tc 147 2 PeopleCircle(再见约瑟夫环)
- leetcode[226]:Invert Binary Tree
- 已知s="(XYZ)+*",t="(X+Z)*Y",利用联接,求子串和转换等基本运算,将s转化为t
- leetcode:Invert Binary Tree
- linux命令9--diffstat
- 一道离散化+线段树+扫描线的题
- 将栈S中的元素逆置,使用额外的一个栈L和非数组变量
- JDK安装成功了,环境变量也配置好了,测试代码也可以运行,但是打不开eclipse
- 常用的三种android分包规范
- Odoo进销存(采购、销售、仓库)入门教程 - 下
- commands commence before first target. 报错