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

描述

分子为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;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值