参考:http://blog.csdn.net/sangjinchao/article/details/68953203
问题描述
四平方和定理,又称为拉格朗日定理:
每个正整数都可以表示为至多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
分析:这道题乍一看是一个简单的暴力求解的问题,四个循环跑起来最后两个数据超时。然后就想着怎么减少循环,去掉一个循环,用总数减去前面三个数的平方和,去判断剩下的数remainder,if ((int)Math.sqrt(remainder) == Math.sqrt(remainder)),如果相等则证明最后需要的数就是remainder的开方。
import java.util.Scanner; public class FourSquare { public static void main(String[] args) { // 暴力求解 Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); scanner.close(); f(n); } private static void f(int n) { double max = Math.sqrt(n); int a, b, c, d; int remainder = 0; for (a = 0; a <= max; a++) { for (b = a; b <= max; b++) { for (c = b; c <= max; c++) { remainder = (int) (n - a*a - b*b - c*c); //剩余的数 d = (int) Math.sqrt(remainder); //剩余数开方 强制转换 if (Math.sqrt(remainder) == d) { //相等则证明就是这个整数 if (c > d) { //加一个顺序的判断 int temp = c; c = d; d = temp; } System.out.println(a + " " + b + " " + c + " " + d); return ; } } } } } }
欢迎指正 too!