题解 | #将真分数分解为埃及分数#
将真分数分解为埃及分数
https://www.nowcoder.com/practice/e0480b2c6aa24bfba0935ffcca3ccb7b
简单模拟,大力出奇迹
#include <cstdlib> #include <iostream> #include <sstream> #include <string> #include <bits/stdc++.h> using namespace std; long long gcd(long long a, long long b){ return b? gcd(b, a%b) : a; } int main() { string a, b, s; while (getline(cin, s)) { stringstream ss; ss.str(s); getline(ss, a, '/'); getline(ss, b); long long n1 = atoi(a.c_str()); long long n2 = atoi(b.c_str()); long long g = gcd(n1, n2); if(g!=1){ n1 /= g; n2 /= g; } double num = 1.0* n1 / n2; vector<long long> nums; for(int i=2;true;i++){ if(n1==1) { nums.push_back(n2); break; } long long g = gcd(i, n2); if(n1 * i / g >= n2 /g){ n1 = n1 * i / g - n2 / g; n2 = n2 * i / g ; g = gcd(n1, n2); n1 /=g; n2 /=g; nums.push_back(i); } } for(int i=0;i<nums.size();i++){ cout << "1/" << nums[i]; if(i!=nums.size()-1) cout << "+"; } cout << endl; } } // 64 位输出请用 printf("%lld")