Cho hai tỷ số x:y và y:z. Tìm tỷ số chung x:y:z.
Ví dụ: 3:5 và 8:9 → 24:40:45.
Giải thuật
- Để y chung, nhân chéo: x*y2 : y1*y2 : y1*z.
- Hoặc hiệu quả hơn: tìm LCM(y1, y2), rồi x * LCM/y1 : LCM : z * LCM/y2.
Ví dụ mã C++
#include <iostream>
using namespace std;
int calcLcm(int a, int b){
int lcm = 2;
while(lcm <= a*b) {
if( lcm%a==0 && lcm%b==0 ) return lcm;
lcm++;
}
return 0;
}
void calcThreeProportion(int x, int y1, int y2, int z){
int lcm = calcLcm(y1, y2);
cout<<((x*lcm)/y1)<<" : "<<lcm<<" : "<<((z*lcm)/y2);
}
int main() {
int x = 12, y1 = 15, y2 = 9, z = 16;
cout<<"The ratios are\t"<<" x:y = "<<x<<":"<<y1<<"\ty:z = "<<y2<<":"<<z<<endl;
cout<<"The common ratio of three numbers is\t";
calcThreeProportion(x, y1, y2, z);
return 0;
}
Đầu vào
3:5 8:9
Đầu ra
24: 40: 45