The topics are as follows:
Write a program that requires function: to find the combination of the three numbers with different number of 1,2,5 and the number of 100.
Get this topic, a lot of people will immediately in the mind, build an expression: X + 2*y + 5*z = 100, so as long as the program to solve this expression, whether it can solve the problem.
int number = 0,x = 0,y = 0,z = 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 = = 1 )
{
number++
}
}
This answer can be answered, but the efficiency is too low (a total of circulation 100*50*20 times).
So let's analyze it first and then consider how to solve the problem:
Because x+2y+5z=100 so x+2y=100-5z, and z=20x=100 y=50 SO (x+2y) = 100, and (x+5z) is even to Z as a loop, the possible values for X are as follows: Z=0, X=100, 98, 96, ... 0z=1,x=95, 1z=2, ..., x=90, 0z=3, x=85, ..., 1z=4, x=80, ..., 0......z=19, x=5, 3, 1z=20, x=0 Therefore, the total number of combinations is 1. 00 within the even + 95 within the odd + 90 within the even +...+5 odd +1, that is: (51+48) + (46+43) + (41+38) + (36+33) + (31+28) + (26+23) + (21+18) + (16+13) + (11+8) + (6+3) +1 even numbers within an even m (including 0) can be expressed as m/2+1= (m+2)/2 odd numbers within an odd m can also be expressed as (m+2)/2.
int number = 0;
int m = 0;
for (M = 0;m <= 100;m+=5)
{number
+ = (m + 2)/2;
}
This program only needs to loop 21 times, two variables, you can get answers that are many times more efficient than the one above----just because of some simple mathematical analysis this once again proves: computer program = data structure + algorithm, and algorithm is the soul of the program, for any engineering problem, when using software to achieve, It is necessary to select the optimal algorithm to meet the constraints of current resource constraints, user requirements and development time constraints. and must not be able to take the hand, immediately with the most easily think of the algorithm to compile a program.
Below is I in Cfree to raise the trial source code, hope for everyone useful.
#include <stdio.h>
int main (int argc, char *argv[])
{
#if 1
int number = 0;
int m = 0;
for (M = 0;m <= 100;m+=5)
{number
+ = (m + 2)/2;
}
#else
int number = 0,x = 0,y = 0,z = 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 = =)
{
number++;
}
}
#endif
printf ("number =%d\n", number);
return 0;
}