Title description: A chicken for 5 cents, a hen for 3 cents, and a chicken for 3 cents. Use 100 cents to buy a hundred chickens. Among them, a rooster, hen, and chicken must have one. Ask the rooster , Hens, chickens to buy just enough to make up 100 yuan.
Time complexity optimized from 100x100x100 to 10
The first one is to program directly according to the subject conditions:
#include<bits/stdc++.h>
using namespace std;
int main() {
for(int cock = 1; cock <= 100; cock++) {
for(int hen = 1; hen <= 100; hen++){
for(int chick = 1; chick <= 100; chick++) {
if((cock+hen+chick==100)&&(cock*5+hen*3+chick/3==100)&&(chick%3==0)){
cout << "公鸡" << cock << "只,母鸡" << hen << "只,小鸡" << chick << "只" << endl;
}
}
}
}
return 0;
}
The second type ( reduction in scope ): According to the requirements of the title, cock 5<=100,hen 3<=100,chick<=100
ie cock<=20,hen<=33
#include<bits/stdc++.h>
using namespace std;
int main() {
for(int cock = 1; cock <= 20; cock++) {
for(int hen = 1; hen <= 33; hen++){
for(int chick = 1; chick <= 100; chick++) {
if((cock+hen+chick==100)&&(cock*5+hen*3+chick/3==100)&&(chick%3==0)){
cout << "公鸡" << cock << "只,母鸡" << hen << "只,小鸡" << chick << "只" << endl;
}
}
}
}
return 0;
}
The third type ( reduce the number of cycles ): get cock+hen+chick=100 according to the subject requirements
#include<bits/stdc++.h>
using namespace std;
int main() {
for(int cock = 1; cock <= 20; cock++) {
for(int hen = 1; hen <= 33; hen++) {
int chick = 100 - cock - hen;
if((cock*5+hen*3+chick/3==100)&&(chick%3==0)){
cout << "公鸡" << cock << "只,母鸡" << hen << "只,小鸡" << chick << "只" << endl;
}
}
}
return 0;
}
The fourth type ( continue to narrow the scope ): According to the requirements of the topic:
1. cock+hen+chick=100
2. cock 5+hen 3+chick/3=100
can be obtained: cock 7+hen 4=100, cock<=14 ,hen<=25
#include<bits/stdc++.h>
using namespace std;
int main() {
for(int cock = 1; cock <= 14; cock++) {
for(int hen = 1; hen <= 25; hen++) {
int chick = 100 - cock - hen;
if((cock*7+hen*4==100)&&(chick%3==0)){
cout << "公鸡" << cock << "只,母鸡" << hen << "只,小鸡" << chick << "只" << endl;
}
}
}
return 0;
}
The fifth type ( continue to reduce the cycle ): According to the conclusion of the fourth type: cock 7+hen 4=100
hen = (100-cock*7)/4
#include<bits/stdc++.h>
using namespace std;
int main() {
for(int cock = 1; cock <= 14; cock++) {
int hen = (100-cock*7)/4;
int chick = 100 - cock - hen;
if((100-cock*7)%4 == 0 && chick%3==0){
cout << "公鸡" << cock << "只,母鸡" << hen << "只,小鸡" << chick << "只" << endl;
}
}
return 0;
}
The sixth type ( continue to reduce the range ): According to hen = (100-cock*7)/4, hen must be a multiple of four
#include<bits/stdc++.h>
using namespace std;
int main() {
for(int cock = 4; cock <= 14; cock+=4) {
int hen = (100-cock*7)/4;
int chick = 100 - cock - hen;
if((100-cock*7)%4 == 0 && chick%3==0){
cout << "公鸡" << cock << "只,母鸡" << hen << "只,小鸡" << chick << "只" << endl;
}
}
return 0;
}
Run screenshot: