用C++計算將‘n’表示為奇數之和的方法數


給定一個整數n作為輸入。目標是找到可以將‘n’表示為奇數之和的方法的數量。例如,如果n是3,它可以表示為和(1+1+1)和(3),所以共有2種方法。

例如

輸入

n=6

輸出

Count of ways to express ‘n’ as sum of odd integers are: 8

解釋

The ways in which we can express ‘n’ as sum of odd integers −
1. 1+1+1+1+1+1
2. 3+1+1+1
3. 1+3+1+1
4. 1+1+3+1
5. 1+1+1+3
6. 3+3
7. 1+5
8. 5+1

輸入

n=9

輸出

Count of ways to express ‘n’ as sum of odd integers are: 34

解釋

The some of the ways in which we can express ‘n’ as sum of odd integers:
1. 1+1+1+1+1+1+1+1+1
2. 3+3+3
3. 5+3+1
4. 7+1+1
5. ….and other such combinations

以下程式中使用的演算法如下

在這種方法中,我們將檢查將數字表示為奇數之和的方法,這些方法來自之前的數字,即第n-1個和第n-2個數字。方法數將為ways(n-1) + ways(n-2)。

  • 輸入一個整數n。

  • 函式odd_ways(int n)接收一個數字並返回將‘n’表示為奇數之和的方法數。

  • 建立一個長度為n+1的陣列arr,用於儲存將數字表示為奇數之和的方法數。

  • 對於數字0,沒有這樣的方法,因此將arr[0]設定為0。

  • 對於數字1,只有一種方法,因此將arr[1]設定為1。

  • 對於其餘數字,我們可以將arr[i]設定為arr[i-1]+arr[i-2],其中i在2到n之間。

  • 最後,我們得到arr[n],表示將n表示為奇數之和的方法數。

  • 返回arr[n]作為結果。

示例

 線上演示

#include<iostream>
using namespace std;
int odd_ways(int n){
   int arr[n+1];
   arr[0] = 0;
   arr[1] = 1;
   for(int i = 2; i <= n; i++){
      arr[i] = arr[i-1] + arr[i-2];
   }
   return arr[n];
}
int main(){
   int n = 6;
   cout<<"Count of ways to express ‘n’ as sum of odd integers are: "<<odd_ways(n);
   return 0;
}

輸出

如果我們執行上面的程式碼,它將生成以下輸出:

Count of ways to express ‘n’ as sum of odd integers are: 8

更新於:2021年1月5日

239 次檢視

啟動您的職業生涯

完成課程後獲得認證

開始
廣告
© . All rights reserved.