This commit is contained in:
hjp 2011-09-25 10:52:27 +00:00
parent 224ef8747d
commit 27babc338d
3 changed files with 86 additions and 0 deletions

6
collatz/GNUmakefile Normal file
View File

@ -0,0 +1,6 @@
CFLAGS = -Wall -O9
all: collatz collatz2
collatz:
collatz2:

40
collatz/collatz.c Normal file
View File

@ -0,0 +1,40 @@
#include <stdio.h>
#include <stdlib.h>
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);
}
}
}

40
collatz/collatz2.c Normal file
View File

@ -0,0 +1,40 @@
#include <stdio.h>
#include <stdlib.h>
#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;
}