编程分拆正整数

先求正整数J拆分为K个正整数的所有分拆方案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71

#include <iostream>
using namespace std;

int ()
{
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;

t += a[i];
i++;
TF = true;
continue;
}
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;
continue;
}
}

return 0;
}

然后便可算出所有分拆方案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74

#include <iostream>
using namespace std;

int ()
{
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;

t += a[i];
i++;
TF = true;
continue;
}
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;
continue;
}
}
delete[] a;
++m;
}
return 0;
}