利用OpenMP实现埃拉托斯特尼(Eratosthenes)素数筛法并行化
2015-05-09 12:24
1196 查看
1.算法简介
1.1筛法起源
筛法是一种简单检定素数的算法。据说是古希腊的埃拉托斯特尼(Eratosthenes,约公元前274~194年)发明的,又称埃拉托斯特尼筛法(sieve of Eratosthenes)。1.2筛法过程
具体做法是:给出要筛数值的范围 n,找出 以内的素数p1,p2,p3,……,pk。从最小素数2去筛,即把2留下,把2的倍数剔除掉;再用下一个素数,也就是3筛,把3留下,把3的倍数剔除掉;接下去用下一个素数5筛,把5留下,把5的倍数剔除掉;不断重复下去。2.实现代码
代码为Linux平台,可简单修改移植到Windows。使用OpenMP实现简单的并行加速,有关OpenMP的用法,百度搜索“OpenMP简易教程”。#include <cmath> #include <cstdlib> #include <cstring> #include <cstdio> #include <iostream> #include <sys/time.h> #include <cassert> #include <omp.h> using namespace std; typedef unsigned int uint32; typedef unsigned long long int uint64; inline void sieve(uint64 start,uint64 end,uint64& num,int threadNum) { assert(start>1); bool* a =new bool[end+1]; memset(a+2,true,end+1); #pragma omp parallel for num_threads(threadNum) for (uint64 i = 2; i <=(uint64)sqrt(end); i++) { if (a[i]) for (uint64 j = i; i*j <= end; j++) a[i*j] = false; } uint64 prime_num=0; if(start==2) prime_num++; #pragma omp parallel for num_threads(threadNum) reduction(+: prime_num) for (uint64 i =(start%2==0?start+1:start); i <=end ;i += 2) { if (a[i]) prime_num++; } num=prime_num; delete[] a; } int main(int argc,char* argv[]) { if(argc!=4){ fprintf(stderr, "usage: Eratosthenes start_number end_number threadNum\n"); exit(-1); } struct timeval ts,te; uint64 start=atoi(argv[1]); uint64 end=atoi(argv[2]); int threadNum=atoi(argv[3]); uint64 num=0; gettimeofday(&ts,NULL); sieve(start,end,num,threadNum); gettimeofday(&te,NULL); cout<<"count: "<<num<<endl; cout<<"total time: "<<((te.tv_sec-ts.tv_sec)*1000+(te.tv_usec-ts.tv_usec)/1000)<<"ms"<<endl; getchar(); return 0; }
参考文献
[1]百度百科-筛法相关文章推荐
- 利用OpenMP实现埃拉托斯特尼(Eratosthenes)素数筛法并行化
- Sieve of Eratosthenes(埃拉托斯特尼素数筛选法)--java实现
- 素数筛法【Sieve Of Eratosthenes + Sieve Of Euler】
- Eratosthenes筛法的F#实现
- 素数筛法/埃拉托斯特尼筛法(sieve of Eratosthenes)——理解及具体问题
- Eratosthenes筛法--Haskell实现
- 埃拉托斯特尼筛法(Sieve of Eratosthenes)简单c实现
- Eratosthenes筛法
- 14 Eratosthenes 筛选求质数
- Eratosthenes 筛选素数
- sieve of Eratosthenes 找质素
- 每日一小练——Eratosthenes 筛选法
- Eratosthenes筛法
- Eratosthenes筛法求素数
- 数论之素数,包括eratosthenes算法,欧拉函数
- BZOJ 2818 Gcd 线性欧拉筛(Eratosthenes银幕)
- 《程序员密码学》之大数算数&Eratosthenes素数筛选
- 算法:Eratosthenes 筛选求质数
- 两种 eratosthenes 筛法的时间比较,第二种快很多会比较好用
- LeetCode - 204. Count Primes - 埃拉托斯特尼筛法 95.12% - (C++) - Sieve of Eratosthenes