C Language Algorithm 1

Source: Internet
Author: User

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 ();
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.