Huawei pen Questions 3 answers

Source: Internet
Author: User

Write oneProgram, Required function: Obtain the sum of the three numbers, 1, 2, 5, and 100.

For example, the first 100 is a combination, and the fifth one and the 19th five are a combination .... Please use C ++.

 

Answer: The easiest thing to thinkAlgorithmYes:

Set X to the number of 1, Y to the number of 2, Z to the number of 5, and number to the combination.

Note that 0 <= x <=, 0 <= Y <= 50, 0 <= z = 20, so you can program it:

 

 

 
Number = 0; For (x = 0; X <= 100; X ++) for (y = 0; y <= 50; y ++) for (Z = 0; z <= 20; Z ++) if (x + 2 * Y + 5 * z) = 100) number ++; cout <number <Endl;

 

 

The above program has to cycle 100*50*20 times, very low

In fact, this question is an obvious mathematical problem, not simply a programming problem. The solution is as follows:

Because X + 2y + 5z = 100

So X + 2y = 100-5z, and z <= 20x <= 100 Y <= 50

So (x + 2y) <= 100, and (x + 5z) is an even number

Perform a loop on Z. The possible values of X are as follows:

 

Z = 0, x = 100, 98,96,... 0

Z = 1, x = 95, 93,..., 1

Z = 2, x = 90, 88,..., 0

Z = 3, x = 85, 83,..., 1

Z = 4, x = 80, 78,..., 0

......

Z = 19, x = 5, 3, 1

Z = 20, x = 0

 

Therefore, the total number of combinations is an even number less than 100 + an odd number less than 95 + an even number less than 90 + an odd number less than... + 5 + 1,

That is:

51 + 48 + 46 + 43 + ........ 1

 

 

The number of even numbers (including 0) within an even m can be expressed as M/2 + 1 = (m + 2)/2

An odd number within an odd m can also be expressed as (m + 2)/2

 

Therefore, the total number of combinations can be programmed as follows:

 
Number = 0; For (intm = 0; m <= 100; m + = 5) {number + = (m + 2)/2 ;} cout <number <Endl;

This program only needs to loop 21 times and two variables to get the answer, which is much more efficient than the above program.

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.