Algorithms_in_C 1.0.0
Set of algorithms implemented in C.
Loading...
Searching...
No Matches
sol1.c File Reference

Problem 14 solution More...

#include <stdio.h>
#include <stdlib.h>
Include dependency graph for sol1.c:

Functions

long long collatz (long long start_num)
 Computes the length of collatz sequence for a given starting number.
 
int main (int argc, char **argv)
 Main function.
 

Detailed Description

Problem 14 solution

Author
Krishna Vedala

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".

To compile with supporintg gcc or clang, the flag "-fopenmp" should be passes while with Microsoft C compiler, the flag "/fopenmp" should be used. If you are using the provided CMAKE compilation, it will automatically detect OPENMP and compile with it for you.

Automatically detects for OPENMP using the _OPENMP macro.

Function Documentation

◆ collatz()

long long collatz ( long long  start_num)

Computes the length of collatz sequence for a given starting number.

28{
29 long long length = 1;
30
31 while (start_num != 1) /* loop till we reach 1 */
32 {
33 if (start_num & 0x01) /* check for odd */
34 start_num = 3 * start_num + 1;
35 else
36 start_num >>= 1; /* simpler divide by 2 */
37 length++;
38 }
39
40 return length;
41}

◆ main()

int main ( int  argc,
char **  argv 
)

Main function.

45{
46 long long max_len = 0, max_len_num = 0;
47 long long MAX_NUM = 1000000;
48
49 if (argc ==
50 2) /* set commandline argumnet as the maximum iteration number */
51 {
52 MAX_NUM = atoll(argv[1]);
53 printf("Maximum number: %lld\n", MAX_NUM);
54 }
55
56 long long i;
57#ifdef _OPENMP
58#pragma omp parallel for shared(max_len, max_len_num) schedule(guided)
59#endif
60 for (i = 1; i < MAX_NUM; i++)
61 {
62 long long L = collatz(i);
63 if (L > max_len)
64 {
65 max_len = L; /* length of sequence */
66 max_len_num = i; /* starting number */
67 }
68
69#if defined(_OPENMP) && defined(DEBUG)
70 printf("Thread: %2d\t %3lld: \t%5lld\n", omp_get_thread_num(), i, L);
71#elif defined(DEBUG)
72 printf("%3lld: \t%5lld\n", i, L);
73#endif
74 }
75
76 printf("Start: %3lld: \tLength: %5lld\n", max_len_num, max_len);
77
78 return 0;
79}
long long collatz(long long start_num)
Computes the length of collatz sequence for a given starting number.
Definition sol1.c:27
Definition list.h:8
Here is the call graph for this function: