四平方和定理,又称为拉格朗日定理:
每个正整数都可以表示为至多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
请严格按要求输出,不要画蛇添足地打印类似:“请您输入...” 的多余内容。所有代码放在同一个源文件中,调试通过后,拷贝提交该源码。
注意:不要使用package语句。不要使用jdk1.7及以上版本的特性。
注意:主类的名字必须是:Main,否则按无效代码处理。
代码:
//存放 四平方和的数字
public static int[] tmp = new int[4];
//找到第一个后,标识一下
public static boolean flg;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//循环输入
while(sc.hasNextInt()) {
int input = sc.nextInt();
//求出它的 算术平方根
int n = (int) Math.sqrt(input);
//由于 flg 是个静态成员变量,所以在这里初始化下
flg = false;
//开始 递归寻找 数字
dfs(0,input,n);
System.out.println(tmp[0]+" "+tmp[1]+" "+tmp[2]+" "+tmp[3]);
}
}
/**
* 用来寻找平方和数字
* @param depth 记录寻找到的数字
* @param input 输入的数
* @param n 最大能够尝试的数字
*/
private static void dfs(int depth, int input, int n) {
//找到了 4 个数
if(depth == 4) {
//检查 四平方 和 是不是 等于 input
if(check(input)) {
//排升序
Arrays.sort(tmp);
//标记下
flg = true;
}
return;
}
//如果有一次递归进来标记是 true,表示已经找到了,直接返回
if(flg == true) {
return;
}
//循环尝试 0 - n 的数字
for(int i = 0; i <= n; i++) {
//判断找到第一组没有
if(flg == true) {
return;
}else {
//将这个数字 放到 tmp 中去
tmp[depth] = i;
//递归寻找下一个数字
dfs(depth+1,input,n);
}
}
}
/**
* 检查当前的 四个数字 能不能满足 四平发和 == input
* @param input 输入的数字
* @return 返回 true 和 false
*/
private static boolean check(int input) {
int ret = (int) (Math.pow(tmp[0], 2)+Math.pow(tmp[1], 2)+Math.pow(tmp[2], 2)+Math.pow(tmp[3], 2));
if(ret == input) {
return true;
}
return false;
}
运行结果: