One interview question. 1x + 2y + 5z = N

Source: Internet
Author: User

Write a function int Foo (int n). For the given n, obtain the number of combinations for any {x, y, z}> = 0, 1x + 2y + 5z = n.

# Include <iostream>

Using NamespaceSTD;

Int Foo1 ( Int N)
{
Int Count = 0 ;
For ( Int Z = 0 ; Z <= N/5 ; Z ++)
{
For ( Int Y = 0 ; Y <= (n- 5 * Z )/ 2 ; Y ++)
{
For (Int X = 0 ; X <= (n- 5 * Z- 2 * Y); X ++)
{
Count ++;
} // This loop can be replaced with Count + = N- 5 * Z- 2 * Y + 1
}
}
Return Count;
}

Int Foo2 ( Int N)
{
Int Count = 0 ;
For ( Int Z =0 ; Z <= N/ 5 ; Z ++)
{
For ( Int Y = 0 ; Y <= (n- 5 * Z )/ 2 ; Y ++)
{
Count + = N- 5 * Z- 2 * Y + 1 ;
} // This loop can be replaced, and Y is an incremental series.
}
Return Count;
}

int foo3 ( int N)
{< br> int COUNT = 0 ;
for ( int Z = 0 ; Z <= N/ 5 ; Z ++)
{< br> count + = (n- 5 * z + 2 ) * (N- 5 * z + 2 )/ 4 ;
}< br> return count;
}

IntMain ()
{
Cout <foo1 (10) <Endl;
Cout <foo2 (10) <Endl;
Cout <foo3 (10) <Endl;
System ("Pause");
Return 0;
}

 

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.