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;
}
posted @   wngtk  阅读(371)  评论(0编辑  收藏  举报
编辑推荐:
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
阅读排行:
· DeepSeek 解答了困扰我五年的技术问题。时代确实变了!
· PPT革命!DeepSeek+Kimi=N小时工作5分钟完成?
· What?废柴, 还在本地部署DeepSeek吗?Are you kidding?
· DeepSeek企业级部署实战指南:从服务器选型到Dify私有化落地
· 程序员转型AI:行业分析
点击右上角即可分享
微信分享提示