1.题目
四平方和定理,又称为拉格朗日定理:
每个正整数都可以表示为至多 4 个正整数的平方和。
如果把 0 包括进去,就正好可以表示为 4 个数的平方和。
输入格式
输入一个正整数 N N N
输出格式
输出4个非负整数,按照从小到大排序,中间用空格分开。
数据范围
0 <
N
N
N < 5 * 106
输入样例
5
输出样例
0 0 1 2
2.基本思想
循环暴力枚举a,b,c d 时间超出!考虑优化
优化思想:
时间换空间
·
二分 or 哈希表 存储一半
3.代码实现
暴力枚举 时间复杂度:
O(N^3)
import java.util.Scanner;
public class _1221四平方和 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int a = 0; a * a <= n; a++) {
for (int b = a; a * a + b * b <= n; b++) {
for (int c = b; a * a + b * b + c * c <= n; c++) {
int t = n - a * a - b * b - c * c;
int d = (int) Math.sqrt(t);
if (d * d == t){
System.out.println(a+" "+b+" "+c+" "+d);
return;
}
}
}
}
}
}
二分 时间复杂度:
O( N^2LogN )
import java.io.*;
import java.util.*;
public class _1221四平方和 {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static List<Sum> list = new ArrayList<>();
static class Sum {
int c, d, s;
public Sum(int c, int d, int s) {
this.c = c;
this.d = d;
this.s = s;
}
}
public static void main(String[] args) throws IOException {
int n = Integer.parseInt(br.readLine());
//存入c*c + d*d
for (int c = 0; c * c <= n; c++)
for (int d = 0; c * c + d * d <= n; d++)
list.add(new Sum(c, d, c * c + d * d));
//字典序排序
list.sort(new Comparator<Sum>() {
@Override
public int compare(Sum o1, Sum o2) {
if (o1.s != o2.s) return o1.s - o2.s;
if (o1.c != o2.c) return o1.c - o2.c;
return o1.d - o2.d;
}
});
//枚举符合条件的前两项
for (int a = 0; a * a <= n; a++) {
for (int b = a; a * a + b * b <= n; b++) {
int t = n - a * a - b * b;
//二分查找 t 是否存在与后两项之中
int l = 0, r = list.size() - 1;
while (l < r) {
int mid = l + r >> 1;
if (list.get(mid).s >= t) r = mid;
else l = mid + 1;
}
//如果找到
if (list.get(l).s == t) {
int c = list.get(l).c;
int d = list.get(l).d;
System.out.println(a + " " + b + " " + c + " " + d);
return;
}
}
}
}
}
哈希表 时间复杂度:
O(N^2)
public class _1221四平方和 {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static HashMap<Integer, Integer> map = new HashMap<>();
public static void main(String[] args) throws IOException {
int n = Integer.parseInt(br.readLine());
//将 c*c+d*d 结果存入hashmap
for (int c = 0; c * c <= n; c++)
for (int d = c; c * c + d * d <= n; d++) {
if (!map.containsKey(c * c + d * d))//若哈希表中不存在的话 则存进去 (保证了字典序)
map.put(c * c + d * d, c);
}
//枚举符合条件的前两项
for (int a = 0; a * a <= n; a++) {
for (int b = a; a * a + b * b <= n; b++) {
int t = n - a * a - b * b;
if (map.containsKey(t)) {
int c = map.get(t);
int d = (int) Math.sqrt(n - a * a - b * b - c * c);
System.out.println(a + " " + b + " " + c + " " + d);
return;
}
}
}
}
}