PTA乙级 (1062 最简分数 (20分))

1062 最简分数 (20分)

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

第一次提交:测试点1没过

测试点1的问题在于题目的输入的两个分数,没有说一定前面的比后面的小,所以在前面做了个判断,进行交换;

 第二次提交:AC

 1 #include <iostream>
 2 #include <cstring>
 3 #include <string>
 4 #include <cstdio>
 5 #include <cmath>
 6 #include <algorithm>
 7 using namespace std;
 8 
 9 int divisor(int a,int b);
10 int ndivisor(int *a,int n);
11 int multiple(int a,int b);
12 int nmultiple(int *a,int b);
13 
14 int main()
15 {
16     int n1,m1,n2,m2,k,a[3],n,temp1,temp2;
17     char chr;
18     cin>>n1>>chr>>m1;
19     cin>>n2>>chr>>m2;
20     cin>>k;
21     if(n1*1.0/m1 > n2*1.0/m2) 
22     {
23         temp1=n1;
24         n1=n2;
25         n2=temp1;
26         temp2=m1;
27         m1=m2;
28         m2=temp2;
29      } 
30     a[0]=m1,a[1]=m2,a[2]=k;
31     n=3;
32     int div=ndivisor(a,n);
33     int mul=nmultiple(a,n);
34     bool flag=false;
35     for(int i=mul/m1*n1+1;i<mul/m2*n2;i++)
36     {
37         if((i%(mul/k)==0)&&(divisor(i/(mul/k),k)==1))
38         {
39             if(!flag) cout<<(i/(mul/k))<<"/"<<k;
40             else if(flag) cout<<" "<<(i/(mul/k))<<"/"<<k;
41             flag=true;
42         }
43     }
44 }
45 
46 int divisor(int a,int b)//两个数求最大公约数
47 {
48     int temp;
49     if(a<b)
50     {
51         temp=a;
52         a=b;
53         b=temp;
54     }
55     while(b!=0)
56     {
57         temp=a%b;
58         a=b;
59         b=temp;
60     }
61     return a;
62 }
63 
64 int ndivisor(int *a,int n)//n个数求最大公约数
65 {
66     if(n==1)
67         return(*a);
68     return divisor(a[n-1],ndivisor(a,n-1));
69 }
70 
71 int multiple(int a,int b)//求最小公倍数
72 {
73     int divisor(int a,int b);
74     int temp=divisor(a,b);
75     return(a*b/temp);
76 }
77 
78 
79 int nmultiple(int *a, int n)//求n个数的最小公倍数
80 {
81     if (n == 1)
82         return *a;
83     else
84         return multiple(a[n-1], nmultiple(a, n-1));
85 }

猜你喜欢

转载自www.cnblogs.com/jianqiao123/p/12219077.html