四方定理 数论中有著名的四方定理:所有自然数至多只要用四个数的平方和就可以表示。
print?/* 四方定理
数论中有著名的四方定理:所有自然数至多只要用四个数的平方和就可以表示。
我们可以通过计算机验证其在有限范围的正确性。
对于大数,简单的循环嵌套是不适宜的。下面的代码给出了一种分解方案。
请仔细阅读,填写空缺的代码(下划线部分)。
注意:请把填空的答案(仅填空处的答案,不包括题面)存入考生文件夹下对应题号的“解答.txt”中即可。
直接写在题面中不能得分。
*/
import java.util.Scanner;
public class 四方定理 {
public static int f(int n, int a[], int idx) {
if (n==0) // 填空1
return 1;
if (idx == 4)
return 0;
for (int i = (int) Math.sqrt(n); i >= 1; i--) {
a[idx] = i;
if (f(n-i*i, a, idx+1) == 1) // 填空2
return 1;
}
return 0;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
for (;;) {
int number;
System.out.printf("输入整数(1~10亿):");
number = scan.nextInt();
int a[] = { 0, 0, 0, 0 };
int r = f(number, a, 0);
System.out.printf("%s: %d %d %d %d\n", r==1?"有结果":"无结果", a[0], a[1], a[2], a[3]);
}
}
}
/* 四方定理
数论中有著名的四方定理:所有自然数至多只要用四个数的平方和就可以表示。
我们可以通过计算机验证其在有限范围的正确性。
对于大数,简单的循环嵌套是不适宜的。下面的代码给出了一种分解方案。
请仔细阅读,填写空缺的代码(下划线部分)。
注意:请把填空的答案(仅填空处的答案,不包括题面)存入考生文件夹下对应题号的“解答.txt”中即可。
直接写在题面中不能得分。
*/
import java.util.Scanner;
public class 四方定理 {
public static int f(int n, int a[], int idx) {
if (n==0) // 填空1
return 1;
if (idx == 4)
return 0;
for (int i = (int) Math.sqrt(n); i >= 1; i--) {
a[idx] = i;
if (f(n-i*i, a, idx+1) == 1) // 填空2
return 1;
}
return 0;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
for (;;) {
int number;
System.out.printf("输入整数(1~10亿):");
number = scan.nextInt();
int a[] = { 0, 0, 0, 0 };
int r = f(number, a, 0);
System.out.printf("%s: %d %d %d %d\n", r==1?"有结果":"无结果", a[0], a[1], a[2], a[3]);
}
}
}运行结果:[plain]
输入整数(1~10亿):234
有结果: 15 3 0 0
输入整数(1~10亿):4
有结果: 2 0 0 0
输入整数(1~10亿):0
有结果: 0 0 0 0
输入整数(1~10亿):-1
无结果: 0 0 0 0
输入整数(1~10亿):
输入整数(1~10亿):234
有结果: 15 3 0 0
输入整数(1~10亿):4
有结果: 2 0 0 0
输入整数(1~10亿):0
有结果: 0 0 0 0
输入整数(1~10亿):-1
无结果: 0 0 0 0
输入整数(1~10亿):
补充:软件开发 , Java ,