整数的分划问题。
如,对于正整数n=6,可以分划为:
6
5+1
4+2,4+1+1
3+3,3+2+1,3+1+1+1
2+2+2,2+2+1+1,2+1+1+1+1
1+1+1+1+1+1
现在的问题是,对于给定的正整数n,编写算法打印所有划分。
用户从键盘输入n(范围1~10)
程序输出该整数得所有划分。
解题思路:
从n到1进行循环,将n分解,分解得到的数中的最大的数是当前的循环变量,然后在分解得到的数中从后往前依次将大于1的数进行分解,为便于实现这一过程我们将分解完的数存放到链表中。
实现方法:
将将要被分解的数存放到链表第一个结点的位置,然后将其分解,将分解得到的数再存入到链表中,然后在从后往前遍历分解得到的数,依次对大于1的数调用分解函数进行分解。每分解一次便输出一次。
程序代码:
#include<iostream>
#define NULL 0
using namespace std;
typedef struct Mynum{
int x;
struct Mynum *next;
}num,*nump;
nump head;
nump s(nump pot,int i);
void fun(nump px);
int main()
{
int n;
cout<<"please input a integer(1~10):"<<endl;
cin>>n;
cout<<endl<<"现在开始分解:"<<endl;
for(int j = n;j > 0;--j)
{
nump t = new (num);
t->next = NULL;
t->x = n;
//调用是s()函数将n分解成最大值为j的几个数的和的形式
head = s(t,j);
//输出第一次分解后的结果
nump pt = head;
while(pt != NULL)
{
if(pt->next)
cout<<pt->x<<"+";
else cout<<pt->x;
pt = pt->next;
}
//调用fun()函数对第一个数以后的数进行分解
fun(head->next);
cout<<endl;
}
return 0;
}
//将pot的x域中的数分解成最大值为i的n个数的和,并连接到链表中的原来位置
nump s(nump pot,int i)
{
nump q,p,temp;
p = pot;
q = pot;
temp = p->next;
int a = p->x - i;
p->x = i;
while(a >= 1)
{
q = new(num);
if(a > i)
{
a = a - i;
q->x = i;
}
else
{
q->x = a;
a = 0;
}
q->next = NULL;
p->next = q;
p = q;
}
q->next = temp;
return pot;
}
//使用该函数对链表中除第一个以外的所有大于1的数调用是s()函数,自后向前进行分解
void fun(nump px)
{
if(px == NULL) return;
nump q,p;
q = px;
fun(q->next);
if(q->x > 1 && (q->next == NULL || q->next->x == 1))
{
for(int k = q->x - 1;k > 0;--k)
{
q = s(q,k);
//每分解一次就将分解后的结果输出
cout<<",";
p = head;
while(p != NULL)
{
if(p->next)
cout<<p->x<<"+";
else cout<<p->x;
p = p->next;
}
}
//对刚得到的结点中的数进行分解
fun(q);
}
}
运行结果:
please input a integer(1~10):
10
现在开始分解:
10
9+1
8+2,8+1+1
7+3,7+2+1,7+1+1+1
6+4,6+3+1,6+2+1+1,6+1+1+1+1
5+5,5+4+1,5+3+1+1,5+2+1+1+1,5+1+1+1+1+1
4+4+2,4+4+1+1,4+3+1+1+1,4+2+1+1+1+1,4+1+1+1+1+1+1
3+3+3+1,3+3+2+1+1,3+3+1+1+1+1,3+2+1+1+1+1+1,3+1+1+1+1+1+1+1
2+2+2+2+2,2+2+2+2+1+1,2+2+2+1+1+1+1,2+2+1+1+1+1+1+1,2+1+1+1+1+1+1+1+1
1+1+1+1+1+1+1+1+1+1