先求正整数J拆分为K个正整数的所有分拆方案
#include <iostream>
using namespace std;
int main()
{
const int K = 2;
const int J = 4;
int a[K] = { 0 };
int i, j, t;
bool TF = true;
t = 0;
i = 0;
while (1)
{
if (i == 0)
{
a[i]++;
if (a[i] >= J)
break;
}
else
{
if (TF == true)
{
a[i] = a[i - 1];
}
else
{
++a[i];
}
if (a[i] > J - t)
{
a[i] = 0;
t -= a[i - 1];
i--;
TF = false;
continue;
}
if (i == K - 1)
{
if (t + a[i] == J)
{
for (j = 0; j < K; j++)
{
cout << a[j];
}
cout << endl;
}
TF = false;
continue;
}
}
t += a[i];
i++;
TF = true;
}
return 0;
}
然后便可算出所有分拆方案
#include <iostream>
using namespace std;
int main()
{
const int J = 8; //要分拆的正整数
int m = 2;
while (m <= J)
{
int* a = new int[m]();
int i, j, t;
bool TF = true;
t = 0;
i = 0;
while (1)
{
if (i == 0)
{
a[i]++;
if (a[i] >= J)
break;
}
else
{
if (TF == true)
{
a[i] = a[i - 1];
}
else
{
++a[i];
}
if (a[i] > J - t)
{
a[i] = 0;
t -= a[i - 1];
i--;
TF = false;
continue;
}
if (i == m - 1)
{
if (t + a[i] == J)
{
for (j = 0; j < m; j++)
{
cout << a[j];
}
cout << endl;
}
TF = false;
continue;
}
}
t += a[i];
i++;
TF = true;
}
delete[] a;
++m;
}
return 0;
}