Skip to content

Instantly share code, notes, and snippets.

@scvalex
Created September 29, 2010 20:58
Show Gist options
  • Save scvalex/603547 to your computer and use it in GitHub Desktop.
Save scvalex/603547 to your computer and use it in GitHub Desktop.
Collatz Conjecture with Corutines in C (alliterative!)
#include <stdio.h>
#include <setjmp.h>
void even(int);
void odd(int);
int main(int argc, char *argv[]) {
even(7);
return 0;
}
jmp_buf even_task, odd_task;
void even(int n) {
int aux;
if (!(aux = setjmp(even_task))) {
odd(n);
} else {
n = aux;
}
while (n > 1) {
while (n % 2 == 0) {
printf("Even! %3d / 2 =\n", n);
n /= 2;
}
if (!(aux = setjmp(even_task))) {
longjmp(odd_task, n);
} else {
n = aux;
}
}
printf("Done! 1\n");
}
void odd(int n) {
while (n > 1) {
if (n % 2 == 1) {
printf("Odd! %3d * 3 + 1 =\n", n);
n = 3 * n + 1;
}
int aux;
if (!(aux = setjmp(odd_task))) {
longjmp(even_task, n);
} else {
n = aux;
}
}
}
Odd! 7 * 3 + 1 =
Even! 22 / 2 =
Odd! 11 * 3 + 1 =
Even! 34 / 2 =
Odd! 17 * 3 + 1 =
Even! 52 / 2 =
Even! 26 / 2 =
Odd! 13 * 3 + 1 =
Even! 40 / 2 =
Even! 20 / 2 =
Even! 10 / 2 =
Odd! 5 * 3 + 1 =
Even! 16 / 2 =
Even! 8 / 2 =
Even! 4 / 2 =
Even! 2 / 2 =
Done! 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment