คำอธิบายปัญหา
ให้อัตราส่วน x:y และ y:z หาอัตราส่วนร่วม x:y:z
ตัวอย่าง
x:y = 3:5, y:z = 8:9 → Output: 24:40:45
วิธีการ
ทำให้ y เท่ากันในทั้งสองอัตราส่วน โดยหา LCM ของ y ทั้งสอง (y1 และ y2)
x:y:z = (x × LCM/y1) : LCM : (z × LCM/y2)
ตัวอย่าง
3:5 และ 8:9 → LCM(5,8)=40
x' = 3×40/5 = 24
y' = 40
z' = 9×40/8 = 45
→ 24:40:45
ตัวอย่างโค้ด C++
#include <iostream>
#include <algorithm> // for std::lcm (C++17)
using namespace std;
int calcLCM(int a, int b) {
return std::lcm(a, b); // C++17
// หรือใช้ a / gcd(a,b) * b
}
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=3, y1=5, y2=8, z=9;
cout << "x:y = " << x << ":" << y1 << ", y:z = " << y2 << ":" << z << endl;
cout << "Common ratio: ";
calcThreeProportion(x, y1, y2, z);
return 0;
}
ผลลัพธ์
x:y = 3:5, y:z = 8:9 Common ratio: 24 : 40 : 45
หมายเหตุ
- C++17 มี std::lcm และ std::gcd ใน <numeric>
- ถ้าไม่มี C++17 ให้เขียน gcd/lcm เอง