pat乙1062 最简分数

蹲街弑〆低调 提交于 2020-01-31 01:06:45
#include<iostream>
using namespace std;
struct fraction{//分数结构体
    int up;
    int down;
    fraction()
    {

    }
};
int gcd(int a,int b)//最大公约数
{
    if(b==0)return a;
    else return gcd(b,a%b);
}
bool isbig(fraction a,fraction b)//比较分数大小
{
    int theup=a.up*b.down-a.down*b.up;
    if(theup>0)return 1;
    else return 0;
}
bool iseasy(fraction a)//是否为最简分数
{
    int i=gcd(a.up,a.down);
    if(i==1)return 1;
    else return 0;
}
int main()
{
    fraction a,b,c;
    int i,n=0,k,themax,thegcd,themin,temp;
    float maxup,minup;
    char c1;
    cin>>a.up>>c1>>a.down;
    cin>>b.up>>c1>>b.down;
    cin>>k;
    if(isbig(a,b))//使b为较大的分数
    {
        temp=a.up;
        a.up=b.up;
        b.up=temp;
        temp=a.down;
        a.down=b.down;
        b.down=temp;
    }
    thegcd=gcd(b.down,k);
    maxup=1.0*b.up/(b.down/thegcd)*(k/thegcd);//求分子上界
    themax=int(maxup);
    if(themax==maxup)themax--;
    thegcd=gcd(a.down,k);
    minup=1.0*a.up/(a.down/thegcd)*(k/thegcd);//求分子下界
    themin=int(minup);
    themin++;
    for(i=themin;i<=themax;i++)//计算最简分数个数
    {
        a.up=i;
        a.down=k;
        if(iseasy(a))
        {
            n++;
        }
    }
    for(i=themin;i<=themax;i++)
    {
        a.up=i;
        a.down=k;
        if(iseasy(a))//是最简分数则输出
        {
            n--;
            cout<<a.up<<"/"<<a.down;
            if(n!=0)//按格式输出
            {
                cout<<" ";
            }
        }
    }
    return 0;

}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!