征战蓝桥 —— 2016年第七届 —— C/C++A组第8题——四平方和

题目

四平方和定理,又称为拉格朗日定理:
每个正整数都可以表示为至多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

资源约定:
峰值内存消耗 < 256M
CPU消耗 < 3000ms

请严格按要求输出,不要画蛇添足地打印类似:“请您输入…” 的多余内容。

所有代码放在同一个源文件中,调试通过后,拷贝提交该源码。

注意: main函数需要返回0
注意: 只使用ANSI C/ANSI C++ 标准,不要调用依赖于编译环境或操作系统的特殊函数。
注意: 所有依赖的函数必须明确地在源文件中 #include , 不能通过工程设置而省略常用头文件。

提交时,注意选择所期望的编译器类型。

代码

#include <iostream>
#include <cstdio>
#include <map>
#include <cmath>
using namespace std;

int N;
map<int,int>cache;
int main(int argc, const char * argv[]) {
    scanf("%d",&N);
    for (int c = 0; c*c <=N/2 ; ++c) {
        for (int d = c; c*c+d*d <= N; ++d) {
            if(cache.find(c*c+d*d)==cache.end())
                cache[c*c+d*d]=c;
        }
    }
    for (int a = 0; a*a <=N/4 ; ++a) {
        for (int b = a; a*a+b*b<=N/2 ; ++b) {
            if(cache.find(N-a*a-b*b)!=cache.end()){
                int c = cache[N-a*a-b*b];
                int d=int(sqrt(N-a*a-b*b-c*c));
                printf("%d %d %d %d\n",a,b,c,d);
                return 0;
            }
        }
    }
    return 0;
}

简单代码

#include <iostream>
#include <cmath>
using namespace std;
bool is_int(int x)
{
	double a=sqrt(x);
	int b=a;
	return a-b==0?true:false;
}
int main()
{
	int n;
	cin>>n;
	for(int a=0;a<sqrt(n);a++)
	{
		for(int b=0;b<sqrt(n);b++)
		{
			for(int c=0;c<sqrt(n);c++)
			{
				int x1=a*a+b*b+c*c;
				if(is_int(n-x1))
				{
					int d=n-x1;
	 				cout<<a<<' '<<b<<' '<<c<<' '<<sqrt(d)<<endl;
					goto stop;
				}
			}
		}
	}
	stop:
	return 0;
}
原文地址:https://www.cnblogs.com/AlexKing007/p/12338686.html