Irreducible Sum of Rationals(C語言CodeWars)

解題思路:

(1)對分母求公共的分母

(2)將分子求和,最後求分母分子的最大公約數

#include <stdlib.h>
typedef long long ll;

ll Divisor(ll a,ll b) {
   ll z=b;
   while(a%b!=0) {
      z = a%b;
      a = b;
      b = z;
   }
   return z;
}

int* sumFracts(int lst[][2], int row) {
   int* p = (int*)calloc(2,sizeof(int));
   p[1]=1;
   if(row==0) return p;
   ll sumd = 1,summ = 0;
   for(int i=0;i<row;i++) sumd*=lst[i][1];
   for(int i=0;i<row;i++) summ+=sumd*lst[i][0]/lst[i][1];
   ll div = Divisor(summ,sumd);
   p[0]=summ/div;
   p[1]=sumd/div;
   return p;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章