1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
|
#include <cstdlib>
#include <cstdio>
#include <pthread.h>
#include <cstring>
#include <cmath>
void* GenerateCollatzSequence2(void*);
void* GenerateCollatzSequence(void*);
struct collatz
{
int num;
int sequence;
};
collatz* num1 = new collatz;
collatz *num2 = new collatz;
int mod_sqrt(int num)
{
float num2 = num * 1.0;
num = pow(num2, 0.5) * 1;
return num;
}
bool isPrime(int arr[], int val)
{
int B = mod_sqrt(val);
while( *arr <= B)//it will not check all primes in the array
{
if (val % *arr == 0)
{
return false;
break;
}
arr++;
}
return true;
}
int* extend_arr(int arr[], int length, int val)
{
int* array2 = new int[length + 1];
for (int J = 0; J < length; J++)
array2[J] = arr[J];
array2[length] = val;
delete[] arr;
arr = NULL;
return array2;
}
void* GenerateCollatzSequence(void*)
{
int MAX_SIZE = 0;
int MAX_NUM = 0;
int SIZE = 0;
int NUM;
int * Brry = new int[1];
int sz = 1;
Brry[0] = 2;
for (int u = 3; u < 1000000; u +=2)
if (isPrime(Brry, u))
{
Brry = extend_arr(Brry, sz, u);
sz++;
}
for (;sz > 1;sz--, Brry++)
{
NUM = *Brry;
for (;*Brry > 1; SIZE++)
{
if (*Brry % 2 != 0)
*Brry = (3 * *Brry) + 1;
else
*Brry /= 2;
}
if (MAX_SIZE < SIZE)
{
MAX_SIZE = SIZE;
MAX_NUM = NUM;
}
SIZE = 0;
}
num1->num = MAX_NUM;
num1->sequence = MAX_SIZE;
pthread_exit(&num1);
}
void* GenerateCollatzSequence2(void*)
{
int M_NUM = 0;
int _NUM;
int M_SZ = 0;
int _SZ = 0;
long int temp;
for (int b = 999999; b > 1; b-=2)
{
_NUM = b;
temp = b;
for (;temp > 1; _SZ++)
if (temp % 2 == 0)
temp /= 2;
else
temp = (3 * temp) + 1;
if (M_SZ < _SZ)
{
M_SZ = _SZ;
M_NUM = _NUM;
}
_SZ = 0;
}
num2->num = M_NUM;
num2->sequence = M_SZ;
pthread_exit(&num2);
}
int main(void)
{
pthread_t NumThread, primThread;
pthread_create(&NumThread, NULL, GenerateCollatzSequence2, NULL);
pthread_create(&primThread, NULL, GenerateCollatzSequence, NULL);
pthread_join( NumThread, NULL);
pthread_join( primThread, NULL);
if (num2->sequence > num1->sequence)
printf("The colatz number with the largest sequence is %d with %d sequence(s)\n", num2->num, num2->sequence);
else
printf("The colatz number with the largest sequence is %d with %d sequence(s)\n", num1->num, num1->sequence);
pthread_exit(NULL);
}
|