用 C++ 統計將一個數表示為連續數之和的方法數
給定一個整數 n 作為輸入。目標是找到將 'num' 表示為兩個或多個連續自然數之和的方法數。例如,如果 n 為 3,它可以表示為和 (1+2),所以共有 1 種方法。
例如
輸入
num=6
輸出
Count of ways to express a number as sum of consecutive numbers are: 1
解釋
The ways in which we can express ‘num’ as sum of consecutive natural numbers: 1+2+3
輸入
num=19
輸出
Count of ways to express a number as sum of consecutive numbers are: 1
解釋
The ways in which we can express ‘num’ as sum of consecutive natural numbers: 9+10
以下程式中使用的思路如下 −
在這種方法中,我們將數字表示為 (a + a+1 + a+2…..+ a+i) 的和。
它變成 (a)(L+1) 次 + 1+2+3+4…+i = a*(i+1) + i*(i+1)/2。(i 個自然數的和)num=a*(i+1) + i*(i+1)/2。a= [ num − (i)*(i+1)/2 ] / (i+1)
我們將從 i=1 到 i*(i+1)/2 小於 num 執行此操作。
將一個整數 num 作為輸入。
函式 sum_consecutive(int num) 獲取一個 num 並返回將 'num' 表示為連續自然數之和的方法數。
將初始計數設定為 0。
將臨時變數 res 作為浮點數。
使用 for 迴圈從 i=1 遍歷到 i*(i+1)/2 < num。
計算 [ num − (i)*(i+1)/2 ] / (i+1) 的值並將其儲存在 res 中。
如果 res 是整數(res − (int)res 為 0),則遞增計數。
最後,我們將計數作為將 num 表示為連續自然數之和的方法數。
返回計數作為結果。
示例
#include <bits/stdc++.h> using namespace std; int sum_consecutive(int num){ int count = 0; int temp = num * 2; float res; for (int i = 1; i * (i + 1) < temp; i++){ int store = i + 1; res = (1.0 * num−(i * (i + 1)) / 2) / store; float check = res − (int)res; if(check == 0.0){ count++; } } return count; } int main(){ int num = 20; cout<<"Count of ways to express a number as sum of consecutive numbers are: "<<sum_consecutive(num) << endl; return 0; }
輸出
如果我們執行上述程式碼,它將生成以下輸出:
Count of ways to express a number as sum of consecutive numbers are: 1
廣告