C++ 中求解和方程的非负整数解个数


在本教程中,我们将编写一个程序来查找和方程的非负整数解的个数。

和方程为 x + y + z = n。给定数字 n,你需要找到该方程的解的个数。让我们看一个例子。

输入

2

输出

6

解为

0 0 2
0 1 1
0 2 0
1 0 1
1 1 0
2 0 0

算法

  • 初始化数字 m。

  • 将计数初始化为 0。

  • 编写三个嵌套循环以获取三个数字的所有组合。

    • 检查方程的有效性。

    • 如果当前数字满足方程,则递增计数。

  • 返回计数。

实现

以下是上述算法在 C++ 中的实现

Open Compiler
#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; }

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

如果运行上述代码,则将得到以下结果。

66

更新于: 2021-10-26

169 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告