考虑方程式:a^3 + b^3 = c^3 + d^3
其中:“^”表示乘方。a、b、c、d是互不相同的小于30的正整数。
这个方程有很多解。比如:
a = 1,b=12,c=9,d=10 就是一个解。因为:1的立方加12的立方等于1729,而9的立方加10的立方也等于1729。
当然,a=12,b=1,c=9,d=10 显然也是解。
如果不计abcd交换次序的情况,这算同一个解。
你的任务是:找到所有小于30的不同的正整数解。把a b c d按从小到大排列,用逗号分隔,每个解占用1行。比如,刚才的解输出为:
1,9,10,12
不同解间的顺序可以不考虑。
package exe66_70;
import java.util.ArrayList;
import java.util.List;
public class Exe66 {
static List<Integer> list = new ArrayList<Integer>();
static List<String> in = new ArrayList<String>();
public static void main(String[] args) {
init();
dfs(0);
}
private static void dfs( int begin) {
if (begin>=4) {
check();
return ;
}
for (int i = begin; i < list.size(); i++) {
int temp = list.get(i);
list.set(i, list.get(begin));
list.set(begin, temp);
dfs(begin+1);
temp = list.get(i);
list.set(i, list.get(begin));
list.set(begin, temp);
}
}
private static void check() {
if (!(list.get(0)<list.get(1)&&list.get(2)<list.get(3))){
return ;
}
if (list.get(0)+list.get(1)==list.get(2)+list.get(3)) {
String s = Math.pow(list.get(0), 1d/3)+"+"+Math.rint(Math.pow(list.get(1), 1d/3))
+"="+Math.rint(Math.pow(list.get(2), 1d/3))+"+"+Math.rint(Math.pow(list.get(3), 1d/3));
if (!in.contains(s)) {
System.out.println(Math.rint(Math.pow(list.get(0), 1d/3))+"+"+Math.rint(Math.pow(list.get(1), 1d/3))
+"="+Math.rint(Math.pow(list.get(2), 1d/3))+"+"+Math.rint(Math.pow(list.get(3), 1d/3)));
s=Math.pow(list.get(2), 1d/3)+"+"+Math.rint(Math.pow(list.get(3), 1d/3))
+"="+Math.rint(Math.pow(list.get(0), 1d/3))+"+"+Math.rint(Math.pow(list.get(1), 1d/3));
in.add(s);
}
}
}
private static void init() {
for (int i = 1; i < 30; i++) {
list.add((int) Math.pow(i, 3));
}
}
}
支付宝扫红包,让我能够买杯咖啡,继续创作,谢谢大家!