#include /* No recursion and no towers in memory: every move of the optimal solution can be read straight off the binary digits of its number. */ void hanoi_bits(int n) { const char *names = n % 2 == 1 ? "ABC" : "ACB"; unsigned long long total = (1ULL << n) - 1; for (unsigned long long m = 1; m <= total; m++) { int disk = 1; for (unsigned long long bits = m; (bits & 1) == 0; bits >>= 1) { disk++; } int from = (int)((m & (m - 1)) % 3); int to = (int)(((m | (m - 1)) + 1) % 3); printf("Move disk %d from %c to %c\n", disk, names[from], names[to]); } } int main(void) { hanoi_bits(3); return 0; }