自然數m的立方可寫成m個連續奇數之和

題目:
任何一個自然數m的立方均可寫成m個連續奇數之和。
例如: 1^3=1    2^3=3+5
   3^3=7+9+11  4^3=13+15+17+19
編程實現:輸入一自然數n,求組成n3(立方)的n個連續奇數

分析:
先找到平衡點,平衡點是n的平方(n*n);
n爲奇數時,結果包含平衡點;結果:...n-6,n-4,n-2,n,n+2,n+4,n+6...
特殊的是中間3個數:n-2,n,n+2
n爲偶數時,結果不包含平衡點;結果:...n-5,n-3,n-1,n+1,n+3,n+5...
特殊的是中間的2個數:n-1,n+1
處理好中間特殊的數時,計算兩邊的數就容易了;見如下代碼:

//找到奇數並打印出
public static void findOdd(int n){
List<Integer> ret=new ArrayList<Integer>();
if(n<0){
ret.add(0);
}else if(n==1){
ret.add(1);
}else{
int tempSum=n*n; //計算平方
int toAdd=tempSum;
int toSub=tempSum;
if(tempSum%2==1){ //是奇數,說明是平衡點
toAdd+=2; //此處加減2
toSub-=2;
ret.add(tempSum); //先添加這個奇數
}else {
toAdd+=1; //此處加減1
toSub-=1;
}
for(int i=0;i<n/2;i++){
ret.add(toAdd);
ret.add(toSub);
toAdd+=2;
toSub-=2;
}
}
Object[] tempRet=ret.toArray();
Arrays.sort(tempRet);
for(int i=0;i<tempRet.length;i++){
System.out.print(tempRet[i]+" ");
}
}

有其他想法的同學可以一起討論.
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章