1. 程式人生 > >PAT 1062 最簡分數

PAT 1062 最簡分數

至少 gcd htm 一個 names .cn ble 公約數 out

https://pintia.cn/problem-sets/994805260223102976/problems/994805268334886912

一個分數一般寫成兩個整數相除的形式:/,其中 M 不為0。最簡分數是指分子和分母沒有公約數的分數表示形式。

現給定兩個不相等的正分數 / 和 /,要求你按從小到大的順序列出它們之間分母為 K 的最簡分數。

輸入格式:

輸入在一行中按 / 的格式給出兩個正分數,隨後是一個正整數分母 K,其間以空格分隔。題目保證給出的所有整數都不超過 1000。

輸出格式:

在一行中按 / 的格式列出兩個給定分數之間分母為 K 的所有最簡分數,按從小到大的順序,其間以 1 個空格分隔。行首尾不得有多余空格。題目保證至少有 1 個輸出。

輸入樣例:

7/18 13/20 12

輸出樣例:

5/12 7/12


#include <bits/stdc++.h>

using namespace std;

int a[1111],b[1111];

int gcd(int a,int b)
{
    int c=a%b;
    while(c)
    {
        a=b;
        b=c;
        c=a%b;
    }
    return b;
}

int main()
{
    int N1,N2,M1,M2,K;
    scanf("%d/%d %d/%d %d",&N1,&M1,&N2,&M2,&K);
    int cnt=1;
    int ans=0;
    if(N1*M2>N2*M1)
    {
        swap(N1,N2);
        swap(M1,M2);
    }
    for(int i=1; i<=1000; i++)
    {
        if(N1*K<M1*i&&M2*i<N2*K)
            a[cnt++]=i;
    }
    for(int i=1; i<cnt; i++)
    {
        if(gcd(a[i],K)==1)
        {
            ans++;
            if(ans>1)
            printf(" %d/%d",a[i],K);
            else
                printf("%d/%d",a[i],K);
        }
    }
    return 0;
}

  

PAT 1062 最簡分數