I'm trying to make a calculator for prime numbers.
The program divides n for every number inferior to n. If the remainder of the division was 0 only 1 time (excluding the division for 1), the number is prime. At the start of the program the user is asked to type a number, then calculations are made for every number until the one typed by the user.
This is a non-parallel task, but I am trying to make it parallel by dividing the numbers between cores.
This is the piece of code that divides the task between the threads.
void division(int number)
{
int ithread[8]{};
int sum = 0;
cout << "Preparation..";
/* Calculating how many numbers the checker will check. */
ithread[0] = (int)number*0.125;
ithread[1] = (int)number*0.125;
ithread[2] = (int)number*0.125;
ithread[3] = (int)number*0.125;
ithread[4] = (int)number*0.125;
ithread[5] = (int)number*0.125;
ithread[6] = (int)number*0.125;
ithread[7] = (int)number*0.125;
/* Calculating from what number the checkers will begin.
the first thread will begin from 0. the second checker will begin from the last number the first
did. The third will begin from the sum of numbers checked by first and second and so on. */
thread thread0(noprint, ithread[0], 0);
sum += ithread[0];
thread thread1(noprint, ithread[1], sum);
sum += ithread[1];
thread thread2(noprint, ithread[2], sum);
sum += ithread[2];
thread thread3(noprint, ithread[3], sum);
sum += ithread[3];
thread thread4(noprint, ithread[4], sum);
sum += ithread[4];
thread thread5(noprint, ithread[5], sum);
sum += ithread[5];
thread thread6(noprint, ithread[6], sum);
sum += ithread[6];
thread thread7(noprint, ithread[7], sum);
thread0.join();
cout << "thread1";
thread1.join();
cout << "thread2";
thread2.join();
cout << "thread3";
thread3.join();
cout << "thread4";
thread4.join();
cout << "thread5";
thread5.join();
cout << "thread6";
thread6.join();
cout << "thread7";
thread7.join();
cout << "thread8";
}
The problem is, some threads end before others, and this can be a big problem with big numbers. For example, 4 takes exactly twice as long as 2 to be checked, and 8 takes twice as long as 4. So, if I ask the program to check all the numbers until 1 million, the first thread will check from 0 to 125000, a pretty easy task for nowadays CPUs. The second is going to check from 125000 to 250000, thus being twice as difficult, and so on.
Now I'm looking for two answers: 1. If you know, please tell me how to divide the load equally between threads. 2. Please explain how to make it so the user is able to choose the number of threads. I already imagined how to make thread selection possible up to 64 threads (well, actually it could be made even for 1 trilion threads, it would just require a lot of IFs and an 1 trillion digit array) the problem is not in the code, it's in the math itself. I don't know how to divide the work equally for 8 cores, let alone for a variable amount of cores.