DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Roger has posted 34 posts at DZone. View Full User Profile

Ternary Counting In C

12.05.2008
| 2326 views |
  • submit to reddit
        // 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.

int countInTernary(int numdigits) {
    char num[numdigits+1];
    memset(num, '0', sizeof num);
    num[numdigits] = 0;
    char *curIndex = &num[numdigits-1];
    char *end = &num[numdigits-1];
    char *start = &num[0];
    bool done = false;
    
    while (!done) {
        printf("%s\n", num);
        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;
}
    
    Tags:
  • C