使用线程计算素数

Calculate prime numbers using threads

本文关键字:计算 线程      更新时间:2023-10-16

我必须通过线程计算范围之间的素数。示例程序运行

./myProg 100 250 4 //4 number of threads and 100 to 250 is range

我做了基础部分,下一步是什么?

#include<iostream>
#include<pthread.h>
#include<string>
#include<cstdlib>
using namespace std;
void* prime(void*);//calculate prime number for this thread between range x to y ???
int main(int argc, char** argv){
    if(argc!=4){
        cout<<"Must provide exactly 3 arguments"<<endl;
        exit(EXIT_FAILURE);
        }
    pthread_t threads[(*argv[3])];
    cout<<"Prime numbers will be calculated by "<<(*argv[3])<<" threads"<<endl;

    return 0;
}

只需对每个范围中的每个值使用Rabin-Miller素性测试,就可以实现这一点。Rabbin-Miller算法不依赖于先前值的素性计算,因此所有线程都可以在没有任何通信的情况下孤立运行。

参见:

  • https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test
  • 算法简介