MPI_Gather 素数数组合并为一个数组

MPI_Gather prime number arrays into one array

我正在尝试拆分一个计算数字是否为质数的程序。因此,我将一系列数字分散到每个进程中,并找到该范围内的素数。这行得通,每个进程都采用范围并找到正确的素数。然后,当我想将每个进程的所有数组收集到一个中时,我 运行 遇到了问题。

要么它打印出正确数量的数组值,但有额外的 0,因此它会打印出类似 2,3,5,7,0,11,13,0,0,0,17,19... 的内容,或者我在 memcpy 参数内存范围重叠的地方得到断言失败错误。

下面是我的main中的相关代码-

  thesePrimes = (int*)malloc(sizeof(int) * maxNumberOfTotalPrimes);

  //findPrimes returns k which is the number of primes found and
  //puts all of the prime numbers from this process into thesePrimes.
  //n is the highest number to check if prime (ie n = 100 check for primes
  //less than 100)
  k = findPrimes(thesePrimes, start, end, n);

  //Reduce k to get the total number of primes within the input
  MPI_Reduce(&k, &numberOfPrimes, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);

  //Allocate just enough space to hold all of the primes based on the reduced
  //number of primes
  allPrimes = (int*)malloc(sizeof(int) * numberOfPrimes);

  //Gather each process's thesePrimes into allPrimes using k as the buffer
  //size since k is the number of primes for the process, just send k numbers
  MPI_Gather(thesePrimes, k, MPI_INT, allPrimes, k, MPI_INT, 0, MPI_COMM_WORLD);

  if(myRank == 0) {
    printf("Attempting to print...\n");
    for(i = 0; i < numberOfPrimes; i++)
        printf("allPrimes[%d]=%d\n", i, allPrimes[i]);

    printf("There are %d prime numbers in the range 0 to %d\n", numberOfPrimes, n);
  }

这是我计算素数个数的函数 -

int findPrimes(int primes[], int start, int end, int n){
    //k is used to count the number of primes
    int i, j, maxJ, k = 0;
    int isPrime = 1;

    printf("Finding primes from %d to %d\n", start, end);

    if(end > n) end = n;
    if(start == 0) start = 2;

    for(i = start; i <= end; i++) {
        maxJ = sqrt(i);

        for(j = 2; j <= maxJ; j++) {
            if(i%j == 0) {
                isPrime = 0;
                break;
            }
        }
        printf("Checking if %d is prime...\n", i);
        if(isPrime) {
         primes[k++] = i;
         printf("%d is a prime number.\n", primes[k-1]);
        }
        else isPrime = 1;
//      printf("Prime check complete.\n");
    }
    printf("k = %d\n", k);
    return k;
}

你需要MPI_Gather()每个等级的素数个数,然后你就能MPI_Gatherv()个素数。