Had no luck getting it to work properly with OpenMP.
Things to look out for when doing this with multithreading:
- compare runs to the current longest runs in the right order i.e. {123,124,125} not {124,123,125} because some threads finish faster than others.
- I have no idea how to transform the do-while loop I'm currently using into an equivalent OMP FOR loop
One idea I had is putting the results of each thread in a run into an array, sorting it and then comparing bit by bit, again, no luck on implementing that.
Here comes the current working (sequential) code:
#include <stdio.h>
#include <stdlib.h>
void main() {
unsigned __int64 a = 0; //running function value
unsigned __int64 r = 0; //current starting value
unsigned __int64 count = 0; //current tree length
unsigned __int64 champ_r = 0; //number with the longest tree
unsigned __int64 champ_count = 0; //number of steps in the longest treetree
do {
count = 0; //reset tree length
r++; //set up the next starting value
a = r;
do {
if (a % 2 != 0) {
a = a * 3 + 1;
count++;
}
if (a % 2 == 0) {
a = a / 2;
count++;
}
} while (a != 1);
if (champ_count <= count) {
champ_r = r;
champ_count = count;
printf("\nNumber of steps for %llu: %llu", champ_r, champ_count);
}
} while (1);
}
And yes, it just keeps running,... Also, I'm using ULL's because why not, might as well run forever.
Good luck!
PS. Other improvements to speed up the code are always appreciated.
EDIT1: switched to unsigned __int64 instead of unsigned long long
EDIT2: This is where I'm currently at, works, but slow
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
void main() {
unsigned __int64 a = 0; //running function value
unsigned __int64 r = 1; //current starting value
unsigned __int64 count = 1; //current tree length
unsigned __int64 champ_r = 0; //number with the longest tree
unsigned __int64 champ_count = 0; //number of steps in the longest tree
do {
#pragma omp parallel private(count) private(a)
{
r++;
a = r;
count = 1;
#pragma omp for
for (int x = 2; x > 1; x++) {
if (a % 2 != 0) {
a = a * 3 + 1;
x = a - 1;
count++;
} else if (a % 2 == 0) {
a = a / 2;
x = a - 1;
count++;
}
}
#pragma omp critical
{
if (champ_count < count) {
champ_r = r;
champ_count = count;
printf("\nAnzahl der Schritte f\x81r %llu : %llu", champ_r, champ_count);
}
count = 1;
}
}
} while (1);
}