关于 多元一次方程 算法的 研究过程
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
2.重构二元一次方程
2.1.首先你会发现两个for是嵌套的 而且里面的内容 基本一致 所以想到可以用 递归来做
2.2.
可以改成
最终重构成这样
从数学角度讲 这就是多元一次方程
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 ); } } }
相关文章推荐
- 关于Floyd-Warshall算法由前趋矩阵计算出的最短路径反映出了算法的执行过程特性的证明
- 关于plsql导入pde因为字符集设置问题报错,而研究oracle服务器字符集、客户端字符集过程中发现的问题看,以及亲测的解决办法
- box2d关于投影预瞄准的算法推演过程
- 关于树分块算法的一些研究
- 关于GC常用算法的研究
- 关于大整数的乘法的算法时间复杂度的计算过程推导(纯属个人推测,请高人指正)
- SQL存储过程分页算法研究(支持千万级)
- 算法设计关于递归方程T(n)=aT(n/b)+f(n)之通用解法
- 关于研究blog的过程
- 关于Qt信号与槽机制的传递方向性研究(结论其实是错误的,但是可以看看分析过程)
- 【总结】关于字符串匹配算法研究
- 关于卡马克算法和系统函数库方法快速开平方根快慢的研究
- 关于循环赛日程表算法的研究
- 有必要澄清两个基本概念--算法和过程的关系以及关于程序设计方法论的一些看法
- 关于最近研究串匹配的过程和总结
- SQL存储过程分页算法研究
- SQL存储过程分页算法研究(支持千万级)
- DOTA2比赛赛前预测算法的研究(二)--关于数据存储,mongoDB的使用
- 关于使用牛顿迭代法和二分法解方程的算法说明
- 算法设计关于递归方程T(n)=aT(n/b)+f(n)之通用解法