Input M and N (20> = m> = n> 0). Program to find the integer sequence I1, I2 ,...., in, so that: I1 + I2 +... + in = m, and I1> = i2....> = in. For example, if n = 4 and M = 8 are input, the following five columns are generated:
5 1 1 1 4 2 1
3 3 1 1 3 2 1
2 2 2 2
--------------------------------------------------------------------------------
This is a friend who asked me a computer exam. The following is my answer. The second one is optimized a bit under the first one. You can try to enter a large number to compare the advantages and disadvantages of the algorithm.
--------------------------------------------------------------------------------
# Include "stdio. H"
Int _ m;
Int _ N;
Int A [20];
Void fun (INT sum, int M, int N)
{
Int I;
If (n <= 0)
{
If (_ m = sum)
{
For (I = 0; I <_ n; I ++) printf ("% 4D", a [I]);
Printf ("\ n ");
}
Return;
}
For (I = m; I> 0; I --)
{
A [_ n-n] = I;
Fun (sum + A [_ n-n], I, n-1 );
}
}
Void main ()
{
_ M = 8;
_ N = 4;
Fun (0, _ m, _ n );
Getchar ();
}
---------------------------------------------------------------------------
# Include "stdio. H"
Int _ m;
Int _ N;
Int A [20];
Void fun (INT sum, int M, int N)
{
Int I;
For (I = m; I> 0; I --)
{
A [_ n-n] = I;
If (n-1 = 0 & sum + A [_ n-n] = _ m)
{
For (I = 0; I <_ n; I ++) printf ("% 4D", a [I]);
Printf ("\ n ");
Return;
}
Else if (sum + A [_ n-n]> = _ m) continue;
Else if (n-1> 0) Fun (sum + A [_ n-n], I, n-1 );
}
}
Void main ()
{
_ M = 20;
_ N = 11;
Fun (0, _ m, _ n );
Getchar ();
}