/ Published in: C
Here's a fairly useless but fun piece of code: counting in base 3. This takes in a number of digits and counts up in ternary. Be warned, though. The algorithm is (for obvious reasons) O(n^3), where n is the number of digits. Actually probably theta(n^3), since n^3 is both the upper and lower bound. Either way, it spits out 531,441 possibilities for 12 digits, so be careful not to run it on too many digits.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
int countInTernary(int numdigits) { char num[numdigits+1]; num[numdigits] = 0; char *curIndex = &num[numdigits-1]; char *end = &num[numdigits-1]; char *start = &num[0]; bool done = false; while (!done) { if (*curIndex < '2') { (*curIndex)++; } else { /* move left until you find a number < 2 */ while (curIndex >= start && *curIndex == '2') { --curIndex; } if (curIndex < start) { done = true; } else { (*curIndex)++; while (curIndex < end) { curIndex++; *curIndex = '0'; } } } } return EXIT_SUCCESS; }