Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

DZone's Guide to

# Ternary Counting In C

·
Free Resource

Comment (0)

Save
{{ articles[0].views | formatCount}} Views
```// 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 = #[numdigits-1];
char *end = #[numdigits-1];
char *start = #[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;
}
``````
Topics:

Comment (0)

Save
{{ articles[0].views | formatCount}} Views

Opinions expressed by DZone contributors are their own.