檢查數字能否表示為 C++ 中連續數字的和
在這裡,我們將瞭解一個數字是否可以表示為兩個或多個連續數字之和。假設一個數字是 12。它可以表示為 3+4+5。
解決這個問題有一個直接且最簡單的方法。如果一個數字是 2 的冪,則它不能表示為一些連續數字的和。我們需要記住兩個事實。
- 任何兩個連續數字的和都是奇數,其中一個為奇數,另一個為偶數。
- 第二個事實是 2n = 2(n-1) + 2(n-1)。
示例
#include <iostream> using namespace std; bool isSumofconsecutiveNumbers(int n) { if((n & (n-1)) && n){ return true; } else { return false; } } int main() { int num = 36; if(isSumofconsecutiveNumbers(num)){ cout << "Can be represented"; } else { cout << "Cannot be represented"; } }
輸出
Can be represented
廣告