华为OJ平台——尼科彻斯定理

题目描述:

  验证尼科彻斯定理,即:任何一个整数m的立方都可以写成m个连续奇数之和。

例如:

  1^3=1 

  2^3=3+5 

  3^3=7+9+11 

  4^3=13+15+17+19 

输入

  输入一个int整数

输出

  输出分解后的string

样例输入

  6

样例输出

  31+33+35+37+39+41

思路:

由例子1~4给出的结论猜测  n3 = (n*(n-1)+1) + (n*(n-1)+2 +1) + ... + (n*(n+1)-2 + 1 )(共n项,等差数列,差为2)

而又等差数列的性质知:

  (n*(n-1)+1) + (n*(n-1)+2 +1) + ... + (n*(n+1)-2 + 1 )

= ((n*(n-1)+1) + (n*(n+1)-2 + 1 ))* n/2

= (n- n + 1  +  n2 + n -1)*n/2

=n3   成立

所以可以直接给出答案

 1 import java.util.Scanner;
 2 /**
 3  * 验证尼科彻斯定理,即:任何一个整数m的立方都可以写成m个连续奇数之和。
 4 例如:
 5   1^3=1 
 6   2^3=3+5 
 7   3^3=7+9+11 
 8   4^3=13+15+17+19 
 9 输入
10   输入一个int整数
11 输出
12   输出分解后的string
13 样例输入
14   6
15 样例输出
16   31+33+35+37+39+41
17  *
18  */
19 public class Nicosiche {
20 
21     public static void main(String[] args) {
22         Scanner cin = new Scanner(System.in) ;    
23         int n = cin.nextInt() ;
24         cin.close();
25         String res = "" ;
26         //输出结果
27         for (int j = n * (n - 1) / 2; j < n * (n + 1) / 2; j++) {
28             if(j != n * (n + 1) / 2 -1){
29                 res += (j*2+1) + "+" ;
30             }else{
31                 res += (j*2+1) ;
32             }            
33         }            
34         System.out.println(res);    
35 
36     }
37 }