The four-square sum theorem, also known as Lagrange's theorem:
Every positive integer can be represented as the sum of squares of at most 4 positive integers.
If 0 is included, it can be expressed as the sum of squares of 4 numbers.
for example:
5=02+02+12+22
7=12+12+12+22
For a given positive integer, there may be multiple representations of the sum of squares.
You are asked to sort 4 numbers:
0≤a≤b≤c≤d
And arrange all possible representations in ascending order according to a, b, c, d as the joint primary key, and finally output the first representation.
input format
Enter a positive integer N.
output format
Output 4 non-negative integers, sorted from small to large, separated by spaces.
data range
0<N<5∗106
Input sample:
5
Sample output:
0 0 1 2
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
int n,i,j,k,l,a,b,c;
int main(){
cin >> n;
for(a = i * i; a * 4 <= n; ++ i, a = i * i)
for(j = i, b = j * j; b * 3 <= n - a; ++ j, b = j * j)
for(k = j, c = k * k; c * 2 <= n - a - b; ++ k, c = k * k){
l=sqrt(n - a - b - c);
if(a + b + c + l * l == n){
cout << i << ' ' << j << ' ' << k << ' ' << l;
return 0;
}
}
return 0;
}
When the first number is violent, because i<=j<=k<=l, so i<=n/4;j<=(ni*i)/3;k<=(ni*ij*j)/2
Think about it again, the program will take a lot of time to calculate the multiplication, so you can define, a=i*i;b=j*j;c=k*k.
Final optimization (the code changes greatly, so it is highlighted with no spaces)
Just AC! ! ! (Although it may happen to be stuck, just pay it a few more times)