描述
分子为1的分数称为埃及分数。现输入一个真分数(分子比分母小的分数,叫做真分数),请将该分数分解为埃及分数。如:8/11 = 1/2+1/5+1/55+1/110。
注:真分数指分子小于分母的分数,分子和分母有可能gcd不为1!
如有多个解,请输出任意一个。
输入描述:
输入一个真分数,String型
输出描述:
输出分解后的string
示例1
输入:
8/11 2/4
复制输出:
1/2+1/5+1/55+1/110 1/3+1/6
复制说明:
第二个样例直接输出1/2也是可以的
#include <iostream>
#include <sstream>
#include <vector>
std::string itoa(int num)
{
std::stringstream oss;
oss << num;
return oss.str();
}
std::string egyptScore(std::string str)
{
std::vector<int> rtnVect;
int index = str.find('/');
int molecule = atoi(str.substr(0, index).c_str());
int denomination = atoi(str.substr(index+1, str.length()-index-1).c_str());
int c = 0;
// std::cout << molecule << " " << denomination << std::endl;
while(1 != molecule)
{
c = denomination / molecule + 1;
molecule = molecule * c - denomination;
denomination = denomination * c;
rtnVect.push_back(c);
if(1 == molecule || 0 == denomination%molecule)
{
rtnVect.push_back(denomination / molecule);
molecule = 1;
}
}
std::string rtnStr = "";
std::vector<int>::iterator iter = rtnVect.begin();
while(iter != rtnVect.end())
{
int temp = *iter;
rtnStr += ("1/" + itoa(temp) + "+");
iter++;
}
return rtnStr;
}
int main()
{
std::string str;
getline(std::cin, str);
std::string rtn = egyptScore(str);
std::cout << rtn.substr(0, rtn.length()-1) << std::endl;
return 0;
}