M
M
Maxim Ivanov2016-04-17 20:56:25
C++ / C#
Maxim Ivanov, 2016-04-17 20:56:25

How to perform parallel mathematical calculations in C++?

I have numbers from 1 to 18446744073709551615. And for each number, the remainder of the division is calculated. But the calculations are endless, I was told what needs to be done in several threads and then everything will be in parallel, but I don’t understand how it is.
Obtaining a prime number of 100%. I ran the first 500 prime numbers in the table, the answer is also 100%. Based on ready-made algorithms (since probabilistic ones cannot be used).

#include <iostream>
#include <biginteger.cpp>
using namespace std;

int main(int argc, char *argv[]) {
    char *text = "274876858367";
    BigInteger n(text), k, q;

    if (n % 2 == 0 || n == 1) {
        cout << "число не является простым" << endl;
        return 0;
    }

    q = n.sqrt() + 1;

    BigInteger m;
    bool prm = true;

    // простые делители
    // начинаются с тройки

    for(k = 3; k <= q; ) {

        // все четные делители и все делители,
        // кратные простым числам, могут быть опущены
        if ((k % 2 == 0) || (k % 3 == 0)) { k++; continue; }

        //m = n%k;
        //cout << "n = " << n << " k = " << k << ", n % k = " << m <<endl;

        if (n % k == 0) {
            prm = false;
            break;
        }

        k++;
    }

    if (prm) cout << "число является простым" << endl;
    else cout << "число не является простым" << endl;

    return 0;
}

Can you give examples please?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Moseychuk, 2016-04-17
@splincodewd

openmp

#include <iostream>

int main(int argc, char* argv[]) {

  #pragma omp parallel for
  for (size_t i = 0; i < 1000000; ++i)
  {
    std::cout << i << std::endl;
  }
}

This particular example runs slower on multiple threads due to I/O synchronization. For efficient use, the result must be accumulated in memory, then output.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question