求primes的算法
来源:互联网 发布:微博如何绑定淘宝 编辑:程序博客网 时间:2024/05/16 01:18
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
0 0
- 求primes的算法
- hdu5901Count primes+Lehmer求1-n的质数个数
- Leetcode:204. Count Primes 求素数的优化问题
- ACM/ICPC 2011 Asia-Amritapuri Site / E Distinct Primes(求数的素因子)
- 求1-1e11内的素数个数(HDU 5901 Count primes )
- HDU --- 5901 Count primes 【求1e11内的素数模板题】
- [算法]求最大公约数的算法
- 求最大公约数的算法
- 求计算器的算法
- 求子集的算法
- 求最大公约数的算法
- 求最大公约数的算法
- 求素数的算法
- 求最大公约数的算法
- 求最大公约数的算法
- 求素数的算法
- 求平方根的算法
- 求平均数的算法
- 使用Apache的ab工具进行压力测试
- alsa和oss声音系统比较
- uva580(数学题)
- 编写算法,对给定的字符串str,返回其最长重复子串及其下标位置
- [安卓]手机管家(四)自定义属性
- 求primes的算法
- js+canvas实现纸牌游戏
- 编写算法,从字符串S中删除所有和字符串t相同的字符
- 二分图
- onCreate
- UnitSearchState API
- 深入学习SlidingMenu
- java学习之IO流2
- ember启动报错