java实现立方和等式

考虑方程式: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 com.liu.ex10;

import java.util.ArrayList;
import java.util.Collections;


public class Main {
    
    public static boolean judge(ArrayList<Integer> tempList) {
        ArrayList<Integer> list = new ArrayList<Integer>();
        for(int i = 0;i < tempList.size();i++)
            list.add(tempList.get(i));
        Collections.sort(list);
        for(int i = 1;i < list.size();i++) {
            if(list.get(i - 1) == list.get(i))
                return false;
        }
        return true;
    }
    
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<String>();
        for(int a = 1;a < 30;a++) {
            for(int b = 1;b < 30;b++) {
                for(int c = 1;c < 30;c++) {
                    for(int d = 1;d < 30;d++) {
                        ArrayList<Integer> tempList = new ArrayList<Integer>();
                        tempList.add(a);
                        tempList.add(b);
                        tempList.add(c);
                        tempList.add(d);
                        if(judge(tempList) == true) {
                            if(a*a*a + b*b*b == c*c*c + d*d*d) {
                                Collections.sort(tempList);
                                String A = ""+tempList.get(0)+","+tempList.get(1)+","+tempList.get(2)+","+tempList.get(3);
                                if(!list.contains(A))
                                    list.add(A);
                            }
                        }
                    }
                }
            }
        }
        
        for(int i = 0;i < list.size();i++)
            System.out.println(list.get(i));
    }
}
原文地址:https://www.cnblogs.com/a1439775520/p/12947953.html