TheAlgorithms-C/project_euler/Problem 14/sol1.c

71 lines
1.8 KiB
C
Raw Normal View History

#include <stdio.h>
#include <stdlib.h>
#ifdef _OPENMP
2020-04-08 21:41:12 +08:00
#include <omp.h>
#endif
/**
2020-04-08 21:41:12 +08:00
* Computes the length of collatz sequence for a given
* starting number
**/
long long collatz(long long start_num)
{
long long length = 1;
2020-04-08 21:41:12 +08:00
while (start_num != 1) /* loop till we reach 1 */
{
2020-04-08 21:41:12 +08:00
if (start_num & 0x01) /* check for odd */
start_num = 3 * start_num + 1;
else
2020-04-08 21:41:12 +08:00
start_num >>= 1; /* simpler divide by 2 */
length++;
}
return length;
}
int main(int argc, char **argv)
{
long long max_len = 0, max_len_num = 0;
long long MAX_NUM = 1000000;
2020-04-08 21:41:12 +08:00
if (argc == 2) /* set commandline argumnet as the maximum iteration number */
2020-03-30 23:42:49 +08:00
{
MAX_NUM = atoll(argv[1]);
2020-03-30 23:42:49 +08:00
printf("Maximum number: %lld\n", MAX_NUM);
}
2020-04-08 21:41:12 +08:00
/**
* Since the computational values for each iteration step are independent,
* we can compute them in parallel. However, the maximum values should be
* updated in synchrony so that we do not get into a "race condition".
2020-04-08 21:41:12 +08:00
*
* To compile with supporintg gcc or clang, the flag "-fopenmp" should be passes
* while with Microsoft C compiler, the flag "/fopenmp" should be used.
2020-04-08 21:41:12 +08:00
*
* Automatically detects for OPENMP using the _OPENMP macro.
**/
2020-04-08 21:41:12 +08:00
#ifdef _OPENMP
#pragma omp parallel for shared(max_len, max_len_num) schedule(guided)
#endif
for (long long i = 1; i < MAX_NUM; i++)
{
long long L = collatz(i);
if (L > max_len)
{
2020-04-08 21:41:12 +08:00
max_len = L; /* length of sequence */
max_len_num = i; /* starting number */
}
2020-04-08 21:41:12 +08:00
#if defined(_OPENMP) && defined(DEBUG)
printf("Thread: %2d\t %3lld: \t%5lld\n", omp_get_thread_num(), i, L);
2020-04-08 21:41:12 +08:00
#elif defined(DEBUG)
printf("%3lld: \t%5lld\n", i, L);
2020-04-08 21:41:12 +08:00
#endif
}
2020-03-30 23:42:49 +08:00
printf("Start: %3lld: \tLength: %5lld\n", max_len_num, max_len);
return 0;
}