"Perhaps the prettiest number system of all... is the balanced ternary notation."——Donald Knuth
平衡三进制(balanced ternary notation),是一种以3为基数,-1(以下用T表示)、0、1为基本数码的进制。
例题:砝码问题
解法1:
枚举
#include <iostream>
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<<w5<<" "<<n<<endl;
cout<<w4<<" "<<m<<endl;
cout<<w3<<" "<<k<<endl;
cout<<w2<<" "<<j<<endl;
cout<<w1<<" "<<i<<endl;
}
}
}
}
}
}
return 0;
}
解法2:
使用平衡三进制
#include <iostream>
using namespace std;
int main(){
cout<<"pls input one number between 1 and 121"<<endl;
int input_Number;
cin>>input_Number;
if (input_Number<0||input_Number>121) {
cout<<"pls input the right number between 1 and 121"<<endl;
return 0;
}
char sign[10];
int temp[10]={0};
int tem=1;
int len=0;
int remainder=0;
int quotient=1;
while (quotient!=0) {
quotient=input_Number/3;
remainder=input_Number%3;
if (remainder==2) {
input_Number=quotient+1;
temp[len]=tem;
sign[len++]='-';
}
if(remainder==1){
input_Number=quotient;
temp[len]=tem;
sign[len++]='+';
}
if (remainder==0) {
input_Number=quotient;
}
tem=tem*3;
}
cout<<temp[len-1];
for (int i=len-2; i>=0; i--) {
cout<<sign[i]<<temp[i];
}
cout<<endl;
return 0;
}
输出所有情况
#include <iostream>
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;
}
参考: