diff --git a/collatz/GNUmakefile b/collatz/GNUmakefile new file mode 100644 index 0000000..42d4c61 --- /dev/null +++ b/collatz/GNUmakefile @@ -0,0 +1,6 @@ +CFLAGS = -Wall -O9 +all: collatz collatz2 + +collatz: + +collatz2: diff --git a/collatz/collatz.c b/collatz/collatz.c new file mode 100644 index 0000000..b1213ea --- /dev/null +++ b/collatz/collatz.c @@ -0,0 +1,40 @@ +#include +#include + +typedef int T; +#define FT "%d" + +int main(void) { + T i = 1; + long c_max = 0; + + for(;;) { + T j = i; + long c = 0; + while (j != 1) { + if (j % 2 == 1) { + T j2 = j * 3 + 1; + if ((j2 - 1) / 3 != j) { + printf(FT " is not 3 * " FT " + 1 at starting point " FT, j2, j, i); + exit(1); + } + j = j2; + } else { + j = j / 2; + } + c++; + } + if (c > c_max) { + printf("new longest sequence starting at " FT ": %ld steps\n", i, c); + c_max = c; + } + + if (i + 1 > i) { + i = i + 1; + } else { + printf(FT " is not greater than " FT "\n", i + 1, i); + exit(1); + } + + } +} diff --git a/collatz/collatz2.c b/collatz/collatz2.c new file mode 100644 index 0000000..0491c61 --- /dev/null +++ b/collatz/collatz2.c @@ -0,0 +1,40 @@ +#include +#include + +#define USE_INT 1 + +#ifdef USE_INT + typedef int T; + #define FT "%d" + #define even(x) ((x) % 2 == 0) +#elif USE_LONG + typedef long T; + #define FT "%ld" + #define even(x) ((x) % 2 == 0) +#elif USE_DOUBLE + typedef double T; + #define FT "%20g" + #define even(x) (floor((x) / 2) == ((x) / 2)) +#endif + +long collatz(T j) { + + long c = 0; + while (j != 1) { + printf("%ld: " FT "\n", c, j); + if (even(j)) { + j = j / 2; + } else { + j = j * 3 + 1; + } + c++; + } + return c; +} + +int main(void) { + T i = 113383; + long c = collatz(i); + printf("%ld\n", c); + return 0; +}