四平方和问题优化:

四平方和定理,又称为拉格朗日定理:
每个正整数都可以表示为至多4个正整数的平方和。
如果把0包括进去,就正好可以表示为4个数的平方和。

比如:
5 = 0^2 + 0^2 + 1^2 + 2^2
7 = 1^2 + 1^2 + 1^2 + 2^2
(^符号表示乘方的意思)

对于一个给定的正整数,可能存在多种平方和的表示法。
要求你对4个数排序:
0 <= a <= b <= c <= d
并对所有的可能表示法按 a,b,c,d 为联合主键升序排列,最后输出第一个表示法


程序输入为一个正整数N (N<5000000)
要求输出4个非负整数,按从小到大排序,中间用空格分开

例如,输入:
5
则程序应该输出:
0 0 1 2

再例如,输入:
12
则程序应该输出:
0 2 2 2

再例如,输入:
773535
则程序应该输出:
1 1 267 838
/*
   四平方和问题优化:
      思路:
         减少枚举变量
         确定枚举范围:
	      a 0--sqrt(5000000/4)
	      b 0--sqrt(5000000/3)
	      c 0--sqrt(5000000/2)
	      d 0--sqrt(5000000)
	 预先求出R=c^2+d^2的解 用unordered_map来保存一个R对应的c。也就是构建哈希表


*/ 
#include <iostream>
#include <unordered_map>
#include <cmath>
using namespace std;
int n;
unordered_map <int, int> f;
int main()
{
	cin >> n;
	for (int c = 0; c*c <= n / 2;c++)
	{
		for (int d = c; c*c + d*d <= n;d++)
		{
			//如果没有找到,将数据保存
			if (f.find(c*c+d*d)==f.end())
			{
				
				f[c*c + d*d] = c;
			}
		}
	}
	for (int a = 0; a*a * 4 <= n;a++)
	{
		for (int b = a; a*a + b*b <= n / 2;b++)
		{
			if (f.find(n - a*a - b*b) != f.end())
			{
				int c = f[n - a*a - b*b];
				int d = int(sqrt(n - a*a - b*b - c*c)*1.0);
				cout << a << " " << b << " " << c << " " << d << endl;
				return 0;
			}
		}
	}

	return 0;
}


猜你喜欢

转载自blog.csdn.net/m0_37806112/article/details/80620176