Blue Bridge Cup – sum of squares problem

Time:2021-1-13

蓝桥杯

For more articles, please pay attention to the official account of “BLOG of the sea”.

Question:

The sum of Squares Theorem is also called Lagrange theorem
Every positive integer can be expressed as the sum of squares of up to four positive integers.
If 0 is included, it can be expressed as the sum of the squares of four numbers.

For example:
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.
You are required to sort 4 numbers:
0 <= a <= b <= c <= d
All possible representations are arranged in ascending order according to a, B, C, D as joint primary key, and the first representation is output at last
Program input is a positive integer n (n < 5000000)
Require the output of four non negative integers, sorted from small to large, separated by spaces in the middle
For example, enter:
5
The program should output:
0 0 1 2
For another example, enter:
12
The program should output:
0 2 2 2
For another example, enter:
773535
The program should output:
1 1 267 838
Resource agreement:
Peak memory consumption < 256M
CPU consumption < 3000ms
Please output in strict accordance with the requirements, do not add superfluous things to the print, similar to: “please input…” The rest of the content.
All the code in the same source file, after debugging, copy and submit the source code.
Note: the main function needs to return 0
Note: only use the ANSI C / ANSI C + + standard, do not call special functions that depend on the compilation environment or operating system.
Note: all dependent functions must be explicitly included in the source file. Common header files cannot be omitted through project settings.
When submitting, choose the type of compiler you want.

Thinking:

I use four cycles to output this problem violently. I used to use four cycles to increase it from small to large, but it’s time-out. I found that the larger the number of input, the smaller the first two numbers of output, but the latter two numbers are larger, so I reduced the last two loops from large to small, so I accepted

Implementation code (c)

#include
#include
void solve(long n){
    int a[4];
    for (a[0]=0; a[0]=a[1]; a[2]--) {
                For (a [3] = sqrt (n-a [1] * a [1] - a [2] * a [2] - a [0] * a [0]) + 1; a [3] > = a [2]; a [3] --) {// in fact, it's the same whether 1 is added or not here
                    if (a[0]*a[0]+a[1]*a[1]+a[2]*a[2]+a[3]*a[3]==n) {
                        printf("%d %d %d %d\n",a[0],a[1],a[2],a[3]);
                        return ;
                    }
                }
            }
        }
    }
}
int main(){
    long n;
    scanf("%ld",&n);
    solve(n);
    return 0;
}

For more articles, please pay attention to the official account of “BLOG of the sea”.