四平方和定理,又稱爲拉格朗日定理:
每個正整數都可以表示爲至多 44 個正整數的平方和。
如果把 00 包括進去,就正好可以表示爲 44 個數的平方和。
比如:
5=02+02+12+225=02+02+12+22
7=12+12+12+227=12+12+12+22
對於一個給定的正整數,可能存在多種平方和的表示法。
要求你對 44 個數排序:
0≤a≤b≤c≤d0≤a≤b≤c≤d
並對所有的可能表示法按 a,b,c,da,b,c,d 爲聯合主鍵升序排列,最後輸出第一個表示法。
輸入格式
輸入一個正整數 NN。
輸出格式
輸出4個非負整數,按從小到大排序,中間用空格分開。
數據範圍
0<N<5∗1060<N<5∗106
輸入樣例:
5
輸出樣例:
0 0 1 2
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
const int N = 2500010;
struct Sum{
int s, c, d;
bool operator < (const Sum &t)const{
if (s != t.s) return s < t.s;
if (c != t.c) return c < t.c;
if (d != t.d) return d < t.d;
}
}sum[N];
int n, m;
int main(){
cin >> n;
for (int c = 0; c * c <= n; c ++)
for (int d = c; d * d + c * c <= n; d ++){
sum[m ++] = {c * c + d * d, c, d};
}
sort(sum, sum + m);
for (int a = 0; a * a <= n; a ++)
for (int b = 0; b * b + a * a <= n; b ++){
int t = n - a * a - b * b;
int l = 0, r = m - 1;
while(l < r){
int mid = l + r >> 1;
if (t <= sum[mid].s) r = mid;
else l = mid + 1;
}
if (sum[l].s == t){
printf("%d %d %d %d\n", a, b, sum[l].c, sum[l].d);
return 0;
}
}
return 0;
}