注意到跟辗转相除有关,直接递归模拟即可,代码非常短且浅显易懂,注意最里层是一个正整数,不应该用花括号包裹。
#include <iostream>
using namespace std;
int main() {
auto f = [](auto &&f, int p, int q)->void {
if (p % q == 0) {
cout << (p / q);
return ;
}
cout << (p / q) << "+1/";
if (q % (p % q) != 0) {
cout << "{";
}
f(f, q, p % q);
if (q % (p % q) != 0) {
cout << "}";
}
} ;
int t; cin >> t;
while (t--) [&]()->void {
int p, q; cin >> p >> q;
cout << p << "/" << q << " = ";
f(f, p, q);
cout << '\n';
}() ;
return 0;
}

京公网安备 11010502036488号