public static IntegerEncoded CreateEncoding(int maxVal) { while (maxVal > 0) { int check = maxVal + 1; // Is maxVal a power of two? if ((check & (check - 1)) == 0) { return(new IntegerEncoded(EIntegerEncoding.JustBits, BitArrayStream.PopCnt(maxVal))); } // Is maxVal of the type 3*2^n - 1? if ((check % 3 == 0) && ((check / 3) & ((check / 3) - 1)) == 0) { return(new IntegerEncoded(EIntegerEncoding.Trit, BitArrayStream.PopCnt(check / 3 - 1))); } // Is maxVal of the type 5*2^n - 1? if ((check % 5 == 0) && ((check / 5) & ((check / 5) - 1)) == 0) { return(new IntegerEncoded(EIntegerEncoding.Quint, BitArrayStream.PopCnt(check / 5 - 1))); } // Apparently it can't be represented with a bounded integer sequence... // just iterate. maxVal--; } return(new IntegerEncoded(EIntegerEncoding.JustBits, 0)); }