ตรวจสอบว่าเลข N แสดงเป็นผลรวมของจำนวนเต็มติดกัน 3 จำนวนได้หรือไม่
ตัวอย่าง: 27 = 8 + 9 + 10
วิธีง่าย: N หาร 3 ลงตัว → เป็นได้ เพราะ (y-1) + y + (y+1) = 3y
ตัวอย่างโค้ด
#include <iostream>
using namespace std;
bool hasThreeNums(int n) {
return (n % 3 == 0);
}
int main() {
int num = 27;
if (hasThreeNums(num)) cout << "Can be represented";
else cout << "Cannot be presented";
}
ผลลัพธ์
Can be represented