首页 > 代码库 > 整数分拆的非递归程序

整数分拆的非递归程序

 

#include<stdio.h>void print_partition(int n){ int i=1;  int m=1;  int h=1;  int t,r;  int a[n+1];  for(;i<n+1;++i)a[i]=1;  a[1]=n;  printf("%d\n",a[1]);  while(a[1]!=1)       {  if(a[h]==2) {a[h--]--;m++;}               else { r=--a[h];                          t=m-h+1;                         while(t>=r){a[++h]=r;t-=r;}                         if(t==0)m=h;                         else m=h+1;                         if(t>=2) {a[++h]=t;}                    }                for(i=1;i<m+1;i++)                printf("%d ",a[i]);                printf("\n");        }}int main(){  int n;   printf("input the number:\n");   scanf("%d",&n);   printf("now output all the partitions of %d:\n",n);   print_partition(n);   return 0;}

  

接下来使用逆字典序打印:

 

#include<stdio.h>void print_partition_inverse(int n){  int a[n+1],i,j,m,h,r;   for(i=1;i<=n;i++){         a[i]=1;         printf("%d ",a[i]);                     }   printf("\n");   a[0]=-1,a[1]=2,h=1,m=n-1;   for(i=1;i<=m;i++){         printf("%d ",a[i]);                   }   printf("\n");   while(a[1]!=n){   if  ( m-h>1)                         { a[++h]=2; m--;}                   else  { j=m-2;                           while (a[j]==a[m-1]) a[j--]=1;                           h=j+1;                           a[h]=a[m-1]+1;                           r=a[m]+a[m-1]*(m-h-1);                           a[m]=1;                           if (m-h>>1) a[m-1]=1;                           m=h+r-1;                         }                         for (i=1;i<=m;i++)                    printf("%d ",a[i]);                    printf("\n");                 }}int main(){  int n;    printf("input the number:\n");    scanf("%d",&n);    printf("now output all the partitions of %d:\n",n);    print_partition_inverse(n);    return 0;}

  

最后是只打印固定长度的分拆:

 

#include<stdio.h>unsigned long int PartOfFixedLength(int n, int k){     if ((n<=0) || (k<=0)) {          printf("Error: Arguments must be positive integers!\n");          return 0;        }     int a[k+2],i;     a[1]=n-k+1,a[k+1]=0;     for(i=2; i<=k; ++i) a[i]=1;     printf("Line 1: ");     for(i=1; i<=k; ++i)     printf(" %d ",a[i]);     printf("\n");           unsigned long int TotalNumbers = 1;     int s,x,j;     int n_div_k = n/k;     int n_mod_k = n%k;     int q = n_div_k + ((n_mod_k == 0)?0:1);     while (a[1]!=q) {            j=2;            s=a[1]-1;            while(a[j]>=a[1]-1)                  s+=a[j++];            if (j<=k)  {                 x=++a[j--];                while(j>1) {                      a[j--]=x;                      s-=x;}                a[1]=s;                       }           TotalNumbers++;           printf("Line %lu: ",TotalNumbers);           for(i=1;i<=k;i++)           printf(" %d ",a[i]);           printf("\n");                     }     return TotalNumbers;           }            

  

 

整数分拆的非递归程序