C++ four square sum (binary search) open left and right open writing method must record the answer!

The four square sum theorem, also known as Lagrange's theorem:

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

If 0 is included, it can be expressed as the sum of the squares of 4 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.

You are required to sort the 4 numbers:

0≤a≤b≤c≤d

And press a, b, c, d for all possible representations

Sort the joint primary key in ascending order, and output the first notation at the end.

Input format

Enter a positive integer N.

Output format

Output 4 non-negative integers, sorted from smallest to largest, separated by spaces.

data range

0<N<5∗10^6

Input sample:

5

Sample output:

0 0 1 2
#include<stdio.h>
#include<algorithm>

using namespace std;

struct Node
{
    int sum,c,d;
    bool operator<(Node &node)//排序规则,书写技巧:越重要,越先判
    {
        if(sum!=node.sum) return sum<node.sum;
        if(c!=node.c) return c<node.c;
        return d<node.d;
    }
}s[5000010];

int n;
int top=0;

int main()
{
    scanf("%d",&n);
    for(int c=0;c*c<n;++c)
    {
        for(int d=c;c*c+d*d<=n;++d)
        {
            s[top++]={c*c+d*d,c,d};
        }
    }
    sort(s,s+top);
    for(int i=0;i<top;++i)
    {
        printf("%d:%d %d %d\n",i,s[i].sum,s[i].c,s[i].d);
    }

    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,r,mid;
            l=-1;r=top;
            int ans;
            while(l+1!=r)//左开右开写法必须及时记录更新答案
            {
                mid=l+((r-l)>>1);
                if(s[mid].sum>=t)
                {
                    r=mid;
                    ans=mid;
                }
                else l=mid;
            }
            if(s[ans].sum==t)
            {
                printf("%d %d %d %d",a,b,s[ans].c,s[ans].d);
                return 0;
            }
        }
    }
}

 

Guess you like

Origin blog.csdn.net/qq_44643644/article/details/108814705