在 C++ 中找到 n 元一次方程的解的数量
本题提供一个 n 元一次方程,如下所示:
coeff1(var1) + coeff2(var2) + … + coeffn(varn) = value
求 n 元一次方程的解的数量。
我们举个例子来理解这个问题:
输入
coeff[] = {3, 1}, value = 4
输出
1
解释
Equation : 3x + y = 4. Solution, x = 0, y = 4.
解决方案
本题的简单解法是计算方程的值。然后通过递归调用更新值。如果值为 0,解的计数为 1。否则,通过减去系数值来递归该值。
展示我们解决方案工作原理的程序:
示例
#include<iostream> using namespace std; int countSolutionsEq(int coeff[], int start, int end, int value) { if (value == 0) return 1; int coefCount = 0; for (int i = start; i <= end; i++) if (coeff[i] <= value) coefCount += countSolutionsEq(coeff, i, end, value - coeff[i]); return coefCount; } int main() { int coeff[] = {3, 5, 1, 2}; int value = 6; int n = sizeof(coeff) / sizeof(coeff[0]); cout<<"The number of solutions of the linear equation is "<<countSolutionsEq(coeff, 0, n - 1, value); return 0; }
输出
The number of solutions of the linear equation is 8
广告