CSU 1404: Four-square Theorem(拉格朗日四平方和定理)

题目:

Description

Lagrange’s four-square theorem states that any natural number can be represented as the sum of four integer squares: n = a2 + b2 + c2 + d2. For example, 3, 31 and 310 can be represented as the sum of four squares as follows: 3 = 12 + 12 + 12 + 02, 31 = 52 + 22 + 12 + 12, 310 = 172 + 42 + 22 + 12.

Given an integer n, represent it by the sum of four integer squares.

This result may be helpful: Any integer n which is not of the form 4a(8m + 7) can be written as a sum of three squares, where a and m are arbitrary non-negative integers. For illustration, 7 = 40 * (8 * 0 + 7), so 7 can not be written as a sum of three squares.

Input

The first line contains the number of test cases T (1 <= T <= 104).

For each test case, there is only one line with an integer n (1 <= n <= 109).

Output

For each test case, output four integers abcd separated by a single space which satisfy n2 = a2 + b2 + c2 + d2. If there are multiple solutions, anyone will be accepted.

Sample Input

5
1
7
7
10
10

Sample Output

1 0 0 0
1 1 1 2
1 2 1 1
1 0 3 0
2 1 1 2


思路:

本来我的思路是利用欧拉四平方和恒等式,不过并没有什么效果,遇到8m+7型的大素数就直接变成暴力枚举了。

这个题目主要是根据给的提示,把不能表示成3个平方和的数拆分成一个尽量大的平方和加上一个可以表示成3个平方和的数

然后再暴力枚举

代码:

#include<iostream>
#include<math.h>
#include<stdio.h>
using namespace std;

bool g(int n)
{
	while (n % 4 == 0)n /= 4;
	return n % 8 == 7;
}

void f(int n)
{
	for (int a = int(sqrt(n));; a--)
	{
		n -= a*a;
		if (n && g(n))
		{
			n += a*a;
			continue;
		}
		for (int b = 0; b*b <= n; b++)
		{
			n -= b*b;
			for (int c = 0; c <= b && c*c <= n; c++)
			{
				n -= c*c;
				int d = int(sqrt(n));
				if (n == d*d)
				{
					printf("%d %d %d %d\n", a, b, c, d);
					return;
				}
				n += c*c;
			}
			n += b*b;
		}		
	}	
}

int main()
{
	int t, n;
	scanf("%d", &t);
	while (t--)
	{
		scanf("%d", &n);
		f(n);
	}
	return 0;
}

/**********************************************************************
	Problem: 1404
	User: 3901140225
	Language: C++
	Result: AC
	Time:76 ms
	Memory:2036 kb
**********************************************************************/


猜你喜欢

转载自blog.csdn.net/nameofcsdn/article/details/80238302