[java] view plaincopyprint /*
考虑方程式: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
不同解间的顺序可以不考虑。
*/
import java.util.ArrayList;
import java.util.Arrays;
import java.util.*;
import java.util.List;
public class 立方和等式 {
public static int[] a = new int [4];
public static boolean[] vis = new boolean[4];
public static List
private static void print(List
for(int i=0;i
}
System.out.println(lis.get(i)[lis.get(i).length-1]);
}
}
public static boolean check(List
if(lis.size()==0){
return true;
}else{
int count = 0;
for(int i=0;i
count = 0;
break;
}else{
count++;
}
}
if(count==4) return false;
}
}
return true;
}
public static boolean check(int[] n){
Set
for(int i=0;i
}
if(sets.size()==4){
return true;
}
return false;
public static void oper(int[] n){
int a = (int)Math.pow(n[0], 3);
int b = (int)Math.pow(n[1], 3);
int c = (int)Math.pow(n[2], 3);
int d = (int)Math.pow(n[3], 3);
if(a+b==c+d){
int[] temp = new int[]{n[0],n[1],n[2],n[3]};
Arrays.sort(temp); // 排序
if(check(lis,temp)){// 不重复,添加
lis.add(temp);
}
}
}
static void f(int m,int start,int end)
{
if(start==end)
{
if(check(a)){
oper(a);
}
return;
}
else
{
for(int i=1;i
if(!vis[start])//没有赋值
{
a[start]=i;
vis[start]=true;
f(m,start+1,end);
vis[start]=false;
}
}
}
}
public static void main(String[] args) {
int m = 30;
int n = 4;
f(m,0,n);
print(lis);
}
}
方法二
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
public class 立方和等式 {
// 输出
private static void print(List
for (int[] i : lis) {
for (int j : i)