四平方和定理,又称为拉格朗日定理:
每个正整数都可以表示为至多 4 个正整数的平方和。
如果把 0 包括进去,就正好可以表示为 4 个数的平方和。
对于一个给定的正整数,可能存在多种平方和的表示法。
要求你对 4 个数排序:
0≤a≤b≤c≤d
并对所有的可能表示法按 a,b,c,d为联合主键升序排列,最后输出第一个表示法。
输入格式:
输入一个正整数 N。
输出格式:
输出4个非负整数,按从小到大排序,中间用空格分开。
数据范围:
0<N<5e6
输入样例:
5
输出样例:
0 0 1 2
第一种方法:暴力破解。
即枚举三个数,第四个数为sqrt(n-a*a-b*b-c*c)。时间复杂度为O(n的三次方),易时间超限
#include<iostream>
#include<cmath>
using namespace std;
const int N=5000010;
int n;
int main()
{
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){
printf("%d %d %d %d\n",a,b,c,d);
return 0;
}
}
}
}
}
第二种算法:用空间来换取时间(哈希算法)
时间复杂度O(n的二次方*logN)
#include<iostream>
#include<utility>//pair的头文件
#include<algorithm>
using namespace std;
#define x first//用x代替first
#define y second//用y代替second
const int N=5e6+10;//即5*10的6次方
int n;
pair<int,int> s[N];
int main()
{
scanf("%d",&n);
for(int c=0;c*c<=n;c++)
{
for(int d=c;c*c+d*d<=n;d++)
{
int t=c*c+d*d;
if(s[t].x==0&&s[t].y==0)
{
s[t].x=c;
s[t].y=d;
}
}
}
for(int a=0;a*a<=n;a++)
{
for(int b=a;b*b+a*a<=n;b++)
{
int t=n-a*a-b*b;
if(s[t].y!=0){
printf("%d %d %d %d\n",a,b,s[t].x,s[t].y);
return 0;
}
}
}
}