110,972
社区成员
发帖
与我相关
我的任务
分享
internal class Cacu
{
//a1X1+a2X2+......+anXn=M;
//a1到an为各元系数
/// <summary>
/// 方程的解的列表
/// </summary>
/// <param name="iRatios">各元系数an</param>
/// <param name="iM">总和</param>
/// <param name="iXLower">各元的下限</param>
/// <param name="iXUpper">各元的上限</param>
internal System.Collections.Generic.List<int[]> CacuIt(int[] iRatios, int iM, int iXLower, int iXUpper)
{
System.Collections.Generic.List<int[]> lAnswers = new List<int[]>();
if (iXLower * iRatios.Length <= iM)//有解
{
int[] iXs = new int[iRatios.Length];
for (int I = 0; I < iXs.Length; I++) iXs[I] = iXLower;
bool blNotEnd = true;
while (blNotEnd)
{
if (GetCacuState(iRatios, iXs, iM))
{
int[] iXt = new int[iRatios.Length];
for (int I = 0; I < iXt.Length; I++) iXt[I] = iXs[I];
lAnswers.Add(iXt);
}
int iIndex = 0;
bool blOverflow = true;
while (blOverflow && iIndex < iXs.Length)
{
int iT = iXs[iIndex] + 1;
if (iT > iXUpper)
{
iXs[iIndex] = iXLower;
iIndex++;
}
else
{
iXs[iIndex] = iT;
blOverflow = false;
}
}
blNotEnd = iIndex < iXs.Length;
}
}
return lAnswers;
}
/// <summary>
/// 算下是不是解
/// </summary>
/// <param name="iRatios">系数表</param>
/// <param name="iXs">当前解</param>
/// <param name="iM">和</param>
/// <returns>计算结果</returns>
internal bool GetCacuState(int[] iRatios, int[] iXs, int iM)
{
int iSum = 0;
for (int I = 0; I < iRatios.Length; I++)
iSum += iRatios[I] * iXs[I];
//if (iSum == iM)
//{
// for (int I = 0; I < iXs.Length; I++)
// Console.Write(string.Format("{0}\t", iXs[I]));
// Console.WriteLine();
//}
return iSum == iM;
}
}
List<string> sl = new List<string>();
/// <summary>
/// 多元一次方程
/// </summary>
/// <param name="n">元数(多少个未知数)</param>
/// <param name="y">方程式的值</param>
/// <param name="cn">当前第几元(未知数)取值</param>
/// <param name="cy">当前取值后的值</param>
/// <param name="slist">取值数列</param>
/// <returns></returns>
public void GetY(int n,int y,int cn,int cy,string slist)
{
string s;
int i, j, k;
s = slist;
for(i=0;i<y;i++)
{
k = cy + i;
s = s + i.ToString() + " ";
if(k<y && cn<n)
{
GetY(n, y, cn + 1, k, s);
}
if(cn==n && k==y)
{
sl.Add(s);
}
}
}