问题描述
四平方和定理,又称为拉格朗日定理: 每个正整数都可以表示为至多 4 个正整数的平方和。
如果把 0 包括进去,就正好可以表示为 4个数的平方和。
比如:
- 5 = 02 + 02 +12 + 22
- 7 = 12 + 12 + 12 + 22
对于一个给定的正整数,可能存在多种平方和的表示法。
要求你对 4 个数排序: 0 ≤ a ≤ b ≤ c ≤ d 并对所有的可能表示法按 a, b, c, d 为联合主键升序排列,最后输出第一个表示法。
输入格式
输入一个正整数 N。
输出格式
输出 4 个非负整数,按从小到大排序,中间用空格分开。
输入样例
5
输出样例
0 0 1 2
数据范围
0
<
N
<
5
×
1
0
6
0 < N < 5 ×10^6
0<N<5×106
题解一(超时)
暴力枚举:
#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int n;
cin >> n;
for (int a = 0; a * a <= n; a ++)
for (int b = a; a * a + b * b <= n; b ++)
for (int c = b; a * a + b * b + c * c <= n; c ++)
for (int d = c; a * a + b * b + c * c + d * d <= n; d ++)
if(a * a + b * b + c * c + d * d == n)
{
printf("%d %d %d %d", a, b, c, d);
return 0;
}
}
题解二(超时)
稍加优化:
#include <cstdio>
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int n;
cin >> n;
for (int a = 0; a * a <= n; a ++)
for (int b = a; a * a + b * b <= n; b ++)
for (int c = b; a * a + b * b + c * c <= n; c ++)
{
int t = n - a * a - b * b - c * c;
int d = sqrt(t);
if(d * d == t && d >= c)
{
printf("%d %d %d %d", a, b, c, d);
return 0;
}
}
}
题解三
二分:
#include <cstdio>
#include <iostream>
#include <algorithm>
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;
return d < t.d;
}
}p[N];
int n, k;
int main()
{
int n;
cin >> n;
for (int c = 0; c * c <= n; c ++)
for (int d = c; c * c + d * d <= n; d ++)
p[k ++] = {c * c + d * d, c, d};
sort(p, p + k);
for (int a = 0; a * a <= n; a ++)
for (int b = a; a * a + b * b <= n; b ++)
{
int t = n - a * a - b * b;
int l = 0, r = k - 1;
while(l < r)
{
int mid = l + r >> 1;
if(p[mid].s >= t) r = mid; // 找到第一个大于等于 t 的位置
else l = mid + 1;
}
if(p[l].s == t)
{
printf("%d %d %d %d\n", a, b, p[l].c, p[l].d);
return 0;
}
}
}