C|balanced ternary notation



"Perhaps the prettiest number system of all... is the balanced ternary notation."——Donald Knuth

平衡三进制(balanced ternary notation),是一种以3为基数,-1(以下用T表示)、0、1为基本数码的进制。



例题:砝码问题


解法1:
枚举

#include using namespace std; int main(){/* *-1,0,1 represent 3 status */int testNum=7; int w1=1; int w2=3; int w3=9; int w4=27; int w5=81; for (int i=-1; i<=1; i++) { for (int j=-1; j<=1; j++) { for (int k=-1; k<=1; k++) { for (int m=-1; m<=1; m++) { for (int n=-1; n<=1; n++) { int tmp=w1*i+w2*j+w3*k+w4*m+w5*n; if (tmp==testNum) { cout<



解法2:
使用平衡三进制

#include using namespace std; int main(){cout<<"pls input one number between 1 and 121"<>input_Number; if (input_Number<0||input_Number>121) { cout<<"pls input the right number between 1 and 121"<=0; i--) { cout<





输出所有情况

#include using namespace std; int main(){int len=0,a[10]={0},j; char op[10]; int t,k,m,input,i; for(j=1; j<=122; j++) { input=j; m=j; len=0; t=1; while(input) { k=input%3; input/=3; //关键是这里的两步 switch(k) { case 0:break; case 1:a[len]=t; op[len++]='+'; break; case 2:a[len]=t; op[len++]='-'; input++; break; } t*=3; } printf("%d=%d",m,a[len-1]); for(i=len-2; i>=0; i--) printf("%c%d",op[i],a[i]); printf("\n"); } return 0; }




参考:
平衡三进制


【C|balanced ternary notation】

    推荐阅读