ตรวจสอบว่าเลข N เป็นผลรวมของจำนวนติดกัน 2 ตัวขึ้นไปได้หรือไม่
ตัวอย่าง: 12 = 3+4+5
ข้อสังเกตสำคัญ: เลขที่เป็นกำลังของ 2 (2ⁿ) ไม่สามารถเขียนเป็นผลรวมจำนวนติดกันได้
เหตุผล: ผลรวมจำนวนติดกัน 2 ตัว = เลขคี่, และ 2ⁿ = 2ⁿ⁻¹ + 2ⁿ⁻¹
วิธีตรวจสอบ: (n & (n-1)) != 0 และ n != 0 → สามารถเขียนได้
ตัวอย่างโค้ด
#include <iostream>
using namespace std;
bool isSumofconsecutiveNumbers(int n) {
return ((n & (n-1)) && n);
}
int main() {
int num = 36;
if (isSumofconsecutiveNumbers(num)) cout << "Can be represented";
else cout << "Cannot be represented";
}
ผลลัพธ์
Can be represented