您好,欢迎来到汇意旅游网。
搜索
您的当前位置:首页HJ82 将真分数分解为埃及分数

HJ82 将真分数分解为埃及分数

来源:汇意旅游网

描述

分子为1的分数称为埃及分数。现输入一个真分数(分子比分母小的分数,叫做真分数),请将该分数分解为埃及分数。如:8/11 = 1/2+1/5+1/55+1/110。

注:真分数指分子小于分母的分数,分子和分母有可能不为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;
}

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- hids.cn 版权所有 赣ICP备2024042780号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务