在 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
廣告
資料結構
網路
關係型資料庫
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式語言
C++
C#
MongoDB
MySQL
JavaScript
PHP