Sum of Squares Theorem , Also known as Lagrange's theorem :

Each positive integer can be expressed as at most 4 Sum of squares of positive integers .

If put 0 Include , It can be expressed as 4 Sum of squares of numbers .

such as :

5=0^2+0^2+1^2+2^2
7=1^2+1^2+1^2+2^2

For a given positive integer , There may be multiple representations of the sum of squares .

Ask you to 4 Number sorting :

0≤a≤b≤c≤d
And for all possible representations a,b,c,d Sort the union primary key in ascending order , Finally, the first representation is output .

Input format
Enter a positive integer N.

Output format
output 4 A nonnegative integer , Sort from small to large , Separate with a space in the middle .

Data range
0<N<5∗106
sample input :
5
sample output :
0 0 1 2
 

violence : Can pass most of the data

But the result timed out
#include <cstdio> using namespace std; const int N = 1e7; int nn ; int main(){
scanf("%d",&nn); for(int i = 0;i<2500;i++){ for(int j = i;j<2500;j++){ for(int
m =j;m<2500;m++){ for(int n = m;n<2500;n++){ if(i*i+j*j+m*m+n*n==nn){
printf("%d %d %d %d",i,j,m,n); return 0; } } } } } return 0; }

optimization :

Lose one layer for loop Two more test points have passed The result still timed out
#include <cstdio> #include <cmath> using namespace std; const double N = 1e7;
double nn ; int main(){ scanf("%lf",&nn); for(double i = 0;i<2500;i++){
for(double j = i;j<2500;j++){ for(double m =j;m<2500;m++){
if(sqrt(nn-i*i-j*j-m*m)==(int)sqrt(nn-i*i-j*j-m*m)){ printf("%d %d %d
%d",(int)i,(int)j,(int)m,(int)sqrt(nn-i*i-j*j-m*m)); return 0; } } } } return
0; }

Optimize the judgment process :
#include <cstdio> #include <cmath> using namespace std; const int N = 1e7; int
nn ; int main(){ scanf("%d",&nn); for(int i = 0;i*i<nn;i++){ for(int j =
i;i*i+j*j<nn;j++){ for(int m =j;i*i+j*j+m*m<nn;m++){ int t = nn-i*i-j*j-m*m;
int k = sqrt(t); if(k*k==t){ printf("%d %d %d %d",i,j,m,k); return 0; } } } } }
 

 

Technology