这篇文章上次修改于 437 天前,可能其部分内容已经发生变化,如有疑问可询问作者。
2025-03-03-java 学习
运行结果


基础任务
由自然数前 n 项立方和公式:
我们可以得到对于公式 1:只需验证
$$
(\frac{56}{2})^2 -(\frac{23}{2})^2 = 6^3
$$对于公式 2:只需验证
$$
(\frac{6970}{2})^2 -(\frac{56}{2})^2 = 180^3
$$
public class Main {
public static void main(String[] args) {
// 验证基本等式
System._out_.println("验证基本等式...\n");
_verifyBasicEquations_();
// 附加任务
System._out_.println("寻找更多的满足条件的整数序列...");
_findMoreSequences_();
}
// 验证基本等式
private static void verifyBasicEquations() {
// 使用自然数立方和公式验证
// 公式:1^3 + 2^3 + ... + n^3 = [n(n+1)/2]^2
// 验证公式1: 3^3 + 4^3 + 5^3 = 6^3
// 等价于 (5*6/2)^2 - (2*3/2)^2 = 6^3
double leftSide1 = Math._pow_(5 * 6.0 / 2, 2) - Math._pow_(2 * 3.0 / 2, 2);
double rightSide1 = Math._pow_(6, 3);
if (Math._abs_(leftSide1 - rightSide1) < 1e-10) {
System._out_.println("公式1:3^3 + 4^3 + 5^3 = 6^3 成立");
System._out_.printf("左边 = %.2f, 右边 = %.2f\n", leftSide1, rightSide1);
} else {
System._out_.println("公式1:3^3 + 4^3 + 5^3 = 6^3 不成立");
}
// 验证公式2: 6^3 + 7^3 + ... + 69^3 = 180^3
// 等价于 (69*70/2)^2 - (5*6/2)^2 = 180^3
double leftSide2 = Math._pow_(69 * 70.0 / 2, 2) - Math._pow_(5 * 6.0 / 2, 2);
double rightSide2 = Math._pow_(180, 3);
if (Math._abs_(leftSide2 - rightSide2) < 1e-10) {
System._out_.println("\n公式2:6^3 + 7^3 + ... + 69^3 = 180^3 成立");
System._out_.printf("左边 = %.2f, 右边 = %.2f\n", leftSide2, rightSide2);
} else {
System._out_.println("\n公式2:6^3 + 7^3 + ... + 69^3 = 180^3 不成立");
}
}
}
附加任务
我的思路是用两个嵌套循环,暴力搜索满足要求的整数序列,使用立方和公式化简来直接计算区间和,避免了循环计算每个数的立方:
对于区间[start, end],使用
代码避免了大量的立方计算,运行速度会比直接使用立方和 + 暴力搜索快。如果想要搜索更大范围的数,只需要修改循环中的上限(1000)即可。
private static void findMoreSequences() {
System._out_.println("找到的满足条件的整数序列:");
for (int start = 1; start < 100; start++) {
for (int end = start; end < 100; end++) {
// 使用立方和公式计算区间[start, end]的立方和
double sum = Math._pow_(end * (end + 1.0) / 2, 2) -
Math._pow_((start - 1) * start / 2.0, 2);
// 计算立方根
double cubeRoot = Math._cbrt_(sum);
// 检查是否为整数
if (Math._abs_(cubeRoot - Math._round_(cubeRoot)) < 1e-10) {
int cubeRootInt = (int) Math._round_(cubeRoot);
// 验证这个序列是否真的满足条件
double verification = Math._pow_(cubeRootInt, 3);
if (Math._abs_(verification - sum) < 1e-10) {
// 只输出有意义的序列(立方根大于序列中的所有数)
if (cubeRootInt > end) {
System._out_.printf("%d^3 + %d^3 + ... + %d^3 = %d^3\n",
start, start + 1, end, cubeRootInt);
}
}
}
}
}
}