Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Kiểm tra số là tổng 3 số nguyên liên tiếp C++


Số N có thể viết thành tổng 3 số nguyên liên tiếp ⇔ N chia hết cho 3.

Chứng minh: (x-1) + x + (x+1) = 3x. N = 3x → x = N/3 nguyên.

Chương trình C++

#include <iostream>
using namespace std;

bool isSumOf3Consecutive(int n) {
    if (n % 3 != 0) return false;
    int x = n / 3;
    cout << n << " = " << (x-1) << " + " << x << " + " << (x+1) << "\n";
    return true;
}

int main() {
    vector test = {27, 12, 15, 10, 9, 6};
    for (int n : test) {
        if (!isSumOf3Consecutive(n))
            cout << n << " khong the bieu dien\n";
    }
    return 0;
}

Kết quả

27 = 8 + 9 + 10
12 = 3 + 4 + 5
15 = 4 + 5 + 6
10 khong the bieu dien
9 = 2 + 3 + 4
6 = 1 + 2 + 3