在C ++中仅使用MPI的谐波级数求和

时间:2018-04-30 16:11:42

标签: c++ parallel-processing

大家都熟悉C ++中的并行计算。我想仅使用MPI(没有其他)并行化C ++中的Harmonic Progression Sum。你们能给我一个合适的起点吗?

我不知道从哪里开始以及如何在并行代码中转换它。

'#include <iostream>
 #include <sstream>

 using namespace std;

 void sum(char* output, const long unsigned int d, const long unsigned int n) 
 {
    long unsigned int digits[d + 11];
    for (long unsigned int digit = 0; digit < d + 11; ++digit) 
    {
        digits[digit] = 0;
    }
    for (long unsigned int i = 1; i <= n; ++i) 
    {
        long unsigned int remainder = 1;
        for (long unsigned int digit = 0; digit < d + 11 && remainder; ++digit)
    {
            long unsigned int div = remainder / i;
            long unsigned int mod = remainder % i;
            digits[digit] += div;
            remainder = mod * 10;
    }
    }
    for (long unsigned int i = d + 11 - 1; i > 0; --i) 
    {
        digits[i - 1] += digits[i] / 10;
        digits[i] %= 10;
    }
    if (digits[d + 1] >= 5) 
    {
        ++digits[d];
    }
    for (long unsigned int i = d; i > 0; --i) 
    {
        digits[i - 1] += digits[i] / 10;
        digits[i] %= 10;
    }
    stringstream stringstreamA;
    stringstreamA << digits[0] << ".";
    for (long unsigned int i = 1; i <= d; ++i) 
    {
        stringstreamA << digits[i];
    }
    stringstreamA << '\0';
    string stringA = stringstreamA.str();
    stringA.copy(output, stringA.size());
}

int main() {

    long unsigned int d, n;

    cin >> d >> n;

    char output[d + 10]; // extra precision due to possible error

    sum(output, d, n);

    cout << output << endl;

    return 0;
}'

由于 亲切的问候

0 个答案:

没有答案