破碎的砝码

来源:互联网 发布:js金额大写转换函数 编辑:程序博客网 时间:2024/04/19 11:00


public class 破碎的砝码 {


/**
* 题目:重40磅的砝码,碎成重量各不等且重量为整数磅的4块。
* 且这4块砝码可以称出1~40   磅直接任意整磅数的重量。求这4块砝码碎片的重量各是多少?
* 分析:A!=B!=C!=D ;A+B+C+D = 40
*/
public static void main(String[] args) {
pieces();
}


public static void pieces(){
for(int i=01;i<=40;i++){
for(int j=i+1;j<=40-i;j++){
for(int m=j+1;m<=40-j-i;m++){
for(int n=m+1;n<=40-m-j-i;n++){
if(i+j+m+n==40){
if(justify(i,j,m,n)==1){
System.out.println(i+" "+j+" "+m+" "+n); 
}
}
}
}
}
}
}

public static int justify(int i,int j,int m,int n){
for(int weight=1;weight<=40;weight++){
if(getWeight(i,j,m,n,weight)==0){
return 0;
}
}
return 1;
}

public static int getWeight(int i,int j,int m,int n,int weight){
for(int x1=-1;x1<=1;x1++){
for(int x2=-1;x2<=1;x2++){
for(int x3=-1;x3<=1;x3++){
for(int x4=-1;x4<=1;x4++){
if(x1*i+x2*j+x3*m+x4*n==weight){ //存在解
return 1;
}
}
}
}
}
return 0;
}
}
1 0
原创粉丝点击