Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

จำนวนคำตอบจำนวนเต็มไม่ติดลบของสมการ x + y + z = n ใน C++


หาจำนวนคำตอบจำนวนเต็มไม่ติดลบของสมการ x + y + z = n

ตัวอย่าง:

Input: 2
Output: 6

คำตอบ: (0,0,2), (0,1,1), (0,2,0), (1,0,1), (1,1,0), (2,0,0)

อัลกอริทึม

  • กำหนด n
  • count = 0
  • วนลูป 3 ชั้น i, j, k:
    • i = 0..n, j = 0..n-i, k = 0..n-i-j
    • ถ้า i+j+k == n count++
  • คืนค่า count

การเขียนโปรแกรม C++

#include <bits/stdc++.h> using namespace std; int getEquationSolutionCount(int n) {    int count = 0;    for (int i = 0; i <= n; i++) {       for (int j = 0; j <= n - i; j++) {          for (int k = 0; k <= n - i - j; k++) {             if (i + j + k == n) count++;           }       }    }    return count; } int main() {    int n = 10;    cout << getEquationSolutionCount(n) << endl;    return 0; }

ผลลัพธ์

66