百钱买百鸡的问题算是一套非常经典的不定方程的问题,题目很简单:公鸡5文钱一只,母鸡3文钱一只,小鸡3只一文钱,
用100文钱买一百只鸡,其中公鸡,母鸡,小鸡都必须要有,问公鸡,母鸡,小鸡要买多少只刚好凑足100文钱。
~~~~~~~~~
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int i=0,j=0,k=0;
for (i=1;i<20;i++){
n=n++;
for (j=1;j<33;j++){
n=n++;
k = 100-i-j;
if (i*5+j*3+ k/3 == 100 && k%3 == 0){
printf("the value of cock is:%d\n",i);
printf("the value of hen is:%d\n",j);
printf("the value of chicken is:%d\n",k);
printf("~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
}
}
}
printf("the total of count is:%d\n",n);
system("pause");
return 0;
}
时间复杂度为O(N2),
优化一点如下,记数器从627变为310:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int i=0,j=0,k=0,n=0;
for (i=1;i<20;i++){
n=n++;
for (j=1;j<((100-5*i)/3);j++){
n=n++;
k = 100-i-j;
if (i*5+j*3+ k/3 == 100 && k%3 == 0){
printf("the value of cock is:%d\n",i);
printf("the value of hen is:%d\n",j);
printf("the value of chicken is:%d\n",k);
printf("~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
}
}
}
printf("the total of count is:%d\n",n);
system("pause");
return 0;
}
如果要成为O(N),则先用方程式多推导,这才是算法的精华。。
先在头脑中过滤,再交给CPU,内存去实施~~
抄其它人的算法如下:
for (int k = 1; k <= 3; k++)
x = 4 * k;
y = 25 - 7 * k;
z = 75 + 3 * k;
推荐BLOG:
http://www.cnblogs.com/huangxincheng/category/401959.html
http://www.cnblogs.com/vamei/default.html?page=1