# 【面试题】求用1，2，5这三个数不同个数组合的和为100的组合个数

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;

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

(51+48)+(46+43)+(41+38)+(36+33)+(31+28)+(26+23)+(21+18)+(16+13)+(11+8)+(6+3)+1

number=0;
for (int m=0;m<=100;m+=5)
{
number+=(m+2)/2;
}
cout<<number<<endl;

#ifdef DEBUG
int simple();
#end if
int optimize();
......
in a function:
{
result=optimize();
ASSERT(result==simple());
}

**************************************************可执行代码******************************************

#include <iostream>
#include <cmath>
using namespace std;

int SimpleSolution();
int optimize();
void main()
{
int number1,number2;
cout<<"求用1，2，5这三个数不同个数组合的和为100的组合个数"<<endl;
number1=SimpleSolution();
cout<<"Simple solution:"<<number1<<endl;
number2=optimize();
cout<<"Optimize solution:"<<number2<<endl;
}

int SimpleSolution()
{
int number(0);
for(int i=0;i<=100;i++)
for(int j=0;j<=50;j++)
for(int k=0;k<=20;k++)
{
if(i+2*j+5*k==100)
number++;
}
return number;
}

int optimize()
{
int number=0;
for(int m=0;m<=100;m+=5)
{
number+=(m+2)/2;
}
return number;
}

posted @ 2011-05-25 19:45  qi09  阅读(2236)  评论(1编辑  收藏