四平方和
四平方和定理,又稱爲拉格朗日定理:
每個正整數都可以表示爲至多4個正整數的平方和。
如果把0包括進去,就正好可以表示爲4個數的平方和。
比如:
5 = 0^2 + 0^2 + 1^2 + 2^2
7 = 1^2 + 1^2 + 1^2 + 2^2
(^符號表示乘方的意思)
對於一個給定的正整數,可能存在多種平方和的表示法。
要求你對4個數排序:
0 <= a <= b <= c <= d
並對所有的可能表示法按 a,b,c,d 爲聯合主鍵升序排列,最後輸出第一個表示法
程序輸入爲一個正整數N (N<5000000)
要求輸出4個非負整數,按從小到大排序,中間用空格分開
例如,輸入:
5
則程序應該輸出:
0 0 1 2
再例如,輸入:
12
則程序應該輸出:
0 2 2 2
再例如,輸入:
773535
則程序應該輸出:
1 1 267 838
資源約定:
峯值內存消耗(含虛擬機) < 256M
CPU消耗 < 3000ms
請嚴格按要求輸出,不要畫蛇添足地打印類似:“請您輸入...” 的多餘內容。
所有代碼放在同一個源文件中,調試通過後,拷貝提交該源碼。
注意:不要使用package語句。不要使用jdk1.7及以上版本的特性。
注意:主類的名字必須是:Main,否則按無效代碼處理。
這裏我嘗試使用遞歸和循環來解, 但當輸入值是773535時,遞歸久久不能得出結果, 所以遞歸算法我只做到了答對部分,循環可以全對
循環解法:
package LanQiao_TrueQuestion;
import java.util.LinkedList;
public class lq_7_8_BaoLi {
static int input=773535;
public static void main(String[] args) {
int sqrtn=(int)Math.sqrt(input);
for(int i= 0;i<sqrtn;i++){
for (int j = 0; j < sqrtn; j++) {
for (int k = 0; k <sqrtn ; k++) {
for (int l = 0; l < sqrtn; l++) {
if(Math.pow(i,2)+Math.pow(j,2)+Math.pow(k,2)+Math.pow(l,2)==input){
System.out.println(i+" "+j+" "+k+" "+l);
return ;
}
}
}
}
}
}
}
遞歸解法:
package LanQiao_TrueQuestion;
import java.util.LinkedList;
public class lq_7_8 {
static int input=5;
static boolean find=false;
static LinkedList<Integer> x;
static LinkedList<Integer> res;
public static void main(String[] args) {
x=new LinkedList<>();
Backtrack(0,0);
System.out.println(res);
}
static void Backtrack (int index, int start){
if(index>3){
return;
}
for (int i = start; i <1000 ; i++) {
if(!find) {
x.addLast(i);
if (Contract(index)) {
System.out.println(x);
return;
}
Backtrack(index + 1, i);
x.removeLast();
}
}
}
private static boolean Contract(int index) {
if(index==3){
return Math.pow(x.get(0),2)+Math.pow(x.get(1),2)+Math.pow(x.get(2),2)+Math.pow(x.get(3),2)==input;
}else{
return false;
}
}
}