验证尼科彻斯定理,即:任何一个整数m的立方都可以写成m个连续奇数之和。
例如:
1^3=1
2^3=3+5
3^3=7+9+11
4^3=13+15+17+19
这题也可以用数学公式推理,首项m*(m-1)+1,循环m次。
package test; import java.util.Scanner; //尼克彻斯定理4^3=13+15+17+19 public class exam14 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (scanner.hasNext()) { int m = scanner.nextInt(); System.out.println(GetSequeOddNum(m)); } scanner.close(); } public static String GetSequeOddNum(int m) { int s = m / 2; int k = m * m; String str = ""; if (m % 2 == 0) { str=String.valueOf(k-1)+"+"+String.valueOf(k+1); for (int i = 1; i < m / 2; i++) { str = String.valueOf(k - 2 * i - 1) + "+" + str + "+" + String.valueOf(k + 2 * i + 1); } } else { str = String.valueOf(k); for (int i = 1; i <= m / 2; i++) { str = String.valueOf(k - 2 * i) + "+" + str + "+" + String.valueOf(k + 2 * i); } } return str; } }