请用c语言实现不重复的整数划分; 划分为k份的整数划分; 划分为奇数和偶数的整数划分
时间: 2024-06-12 22:09:26 浏览: 103
1. 不重复的整数划分的C语言实现:
```c
#include <stdio.h>
void partition(int n, int max, char *str, int depth) {
if (n == 0) {
printf("%s\n", str);
return;
}
if (depth == 0) {
return;
}
for (int i = max; i >= 1; i--) {
if (i <= n) {
char tmp[256];
sprintf(tmp, "%s%d ", str, i);
partition(n - i, i - 1, tmp, depth - 1);
}
}
}
int main() {
int n, k;
printf("请输入一个正整数n:");
scanf("%d", &n);
partition(n, n, "", n);
return 0;
}
```
2. 划分为k份的整数划分的C语言实现:
```c
#include <stdio.h>
void partition(int n, int k, int min, char *str, int depth) {
if (n == 0 && k == 0) {
printf("%s\n", str);
return;
}
if (depth == 0 || k == 0) {
return;
}
for (int i = min; i <= n; i++) {
char tmp[256];
sprintf(tmp, "%s%d ", str, i);
partition(n - i, k - 1, i, tmp, depth - 1);
}
}
int main() {
int n, k;
printf("请输入一个正整数n:");
scanf("%d", &n);
printf("请输入一个正整数k:");
scanf("%d", &k);
partition(n, k, 1, "", n);
return 0;
}
```
3. 划分为奇数和偶数的整数划分的C语言实现:
```c
#include <stdio.h>
void partition(int n, int max, char *str, int depth, int flag) {
if (n == 0) {
printf("%s\n", str);
return;
}
if (depth == 0) {
return;
}
for (int i = max; i >= 1; i--) {
if (i <= n && (i % 2 == flag || flag == -1)) {
char tmp[256];
sprintf(tmp, "%s%d ", str, i);
partition(n - i, i - 1, tmp, depth - 1, i % 2 == 0 ? 0 : 1);
}
}
}
int main() {
int n;
printf("请输入一个正整数n:");
scanf("%d", &n);
partition(n, n, "", n, -1);
return 0;
}
```
阅读全文