7-37 整数分解为若干项之和 (20分)
7-37 整数分解为若干项之和 (20分)
https://pintia.cn/problem-sets/14/problems/2990
对于给定一个数 7 来说
1 1 1 1 1 1 1
1 1 1 1 1 2
1 1 1 1 3
1 1 1 2 2
1 1 1 4
1 1 2 3
1 1 5
1 2 2 2
1 2 4
1 3 3
1 6
2 2 3
2 5
3 4
看到这个,立马想到的就是用一个数组来表达这些数。然后找最后的两个数的规律,要么是后头两个数加起来,要么呢只是一个加一一个减一,可能还会再展开。
不妨直接看代码。
#include <stdio.h>
int main(int argc, char const *argv[])
{
int a[30];
int n, last, i;
// n = 7;
scanf("%d", &n);
// 第一个式子所有的数都是1
for (i = 0; i < n; i++) {
a[i] = 1;
}
last = n-1;
int count = 1;
while (last - 1 >= 0) {
// 输出
printf("%d=", n);
for (i = 0; i <= last; i++) {
printf("%d", a[i]);
if (i != last) {
printf("+");
}
}
if (count % 4 == 0) {
printf("\n");
count = 0;
} else {
printf(";");
}
count++;
// 计算
if (a[last] - a[last-1] <= 1) {
a[last-1] = a[last-1] + a[last];
last--;
} else {
a[last]--;
a[last-1]++;
while (a[last] - a[last-1] >= a[last-1]) {
int t = a[last];
a[last] = a[last-1];
a[last+1] = t - a[last-1];
last++;
}
}
}
printf("%d=%d", n, n);
return 0;
}