ABC三個鄰居的年齡相乘是2450,ABC三個鄰居的和是乙的兩倍,ABC三個鄰居經甲都要小,求五個人的年齡?
代碼如下:
bool Age::mul(int a,int b,int c)
{
return (a*b*c==2450);
}
bool Age::pls(int a,int b,int c)
{
return (a+b+c)%2==0;
}
void Age::arth()
{
typedef pair<int,age> Pair;
int tmp,ave,hit;
for(age_t.a=1;age_t.a<=2450;age_t.a++)
for(age_t.b=1;age_t.b<=age_t.a;age_t.b++)
for(age_t.c=1;age_t.c<=age_t.b;age_t.c++){
if(mul(age_t.a,age_t.b,age_t.c) && pls(age_t.a,age_t.b,age_t.c)){
ave=(age_t.a+age_t.b+age_t.c)/2;
m_age.insert(Pair(ave,age_t));
}
}
m_iter=m_age.begin();
while(true){
tmp=m_age.count(m_iter->first);
if(tmp>1 || m_iter==m_age.end()){
hit=m_iter->first;
break;
}
m_iter++;
}
for(m_iter=m_age.begin();m_iter!=m_age.end();m_iter++){
if(hit==m_iter->first){
cout<<"A may "<<m_iter->second.a<<" years old"<<endl;
cout<<"B may "<<m_iter->second.b<<" years old"<<endl;
cout<<"C may "<<m_iter->second.c<<" years old"<<endl;
cout<<“乙 is "<<m_iter->first<<" years old"<<endl;
cout<<endl;
}
}
}
執行得到結果如下:
A may 49 years old
B may 10 years old
C may 5 years old
乙 is 32 years old
A may 50 years old
B may 7 years old
C may 7 years old
乙 is 32 years old
而A B C都比甲小,如果甲超過50歲,那麽上面這兩個結果不能確定。所以甲必須為50歲,那麽第壹種情況就正好符合要求。所以甲是50歲,乙是32歲,A B C分別為5,10,49歲。