您的位置:首页 > 其它

关于 多元一次方程 算法的 研究过程

2013-03-04 18:44 513 查看
假定在一个陌生的国度,有5种不同的硬币单位15,23,29,41和67(分)。寻找所有组成18元8分(1808分)的可能组合。假定对于所有面值的硬币你都有足够的硬币。

从数学角度讲 这就是多元一次方程

1808 = 15a + 23b + 29c + 41d + 67e 求解a,b,c,d,e的值

1.首先算二元一次方程

6 = 1*a + 2*b

int temp_sum = 6;
boolean isSuccessful = false;
for( int a = 0 ; a <= temp_sum / 1 ; a++ ){
temp_sum -= a * 1;
for( int b = 0 ; b <= temp_sum / 2 ; b++ ){
temp_sum -= b * 2;
if( temp_sum == 0 ){
System.out.println( 1 + "*" + a + " " +
2 + "*" + b + " " );
temp_sum = 6;
isSuccessful = true;
break;
}else{
temp_sum += b * 2;
}
}
if( !isSuccessful ){
temp_sum += a * 1;
}else{
isSuccessful = false;
}
}
这是最初思维的过程 比较容易理解 但是太繁琐 所以需要重构一下

2.重构二元一次方程

2.1.首先你会发现两个for是嵌套的 而且里面的内容 基本一致 所以想到可以用 递归来做

2.2.

temp_sum -= b * 2;
if( temp_sum == 0 ){
System.out.println( 1 + "*" + a + " " + 2 + "*" + b + " " );
temp_sum = 6;
isSuccessful = true;
break;
}else{
temp_sum += b * 2;
}


可以改成

if( ( temp_sum - b * 2 ) == 0 ){
System.out.println( 1 + "*" + a + " " + 2 + "*" + b + " " );
temp_sum = 6;
isSuccessful = true;
break;
}
这样是不是简洁多了

最终重构成这样

public static void getResult(){
int[] factors = {15,23,29,41,67};
getResult( 1808 , factors , 0 , "" );
}

public static void getResult( int temp_sum , int[] factors , int num , String output ){
int factor = factors[ num ] ;
int next_num = num + 1;
for( int a = 0 ; a <= temp_sum / factor ; a++ ){
int result = temp_sum - a * factor ;
String temp_output = output + " + " + factor + " * " + a;
if( result == 0 ){
System.out.println( temp_output );
return ;
}
if( factors.length > next_num ){
getResult( result , factors , next_num , temp_output );
}
}
}



























                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: