-
Notifications
You must be signed in to change notification settings - Fork 19
/
L1-009 N个数求和.cpp
35 lines (35 loc) · 1.04 KB
/
L1-009 N个数求和.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <cstdio>
#include <cstdlib>
using namespace std;
long long gcd(long long a, long long b) {return b == 0 ? a : gcd(b, a % b);}
int main() {
long long n, a, b, suma = 0, sumb = 1, gcdvalue;
scanf("%lld", &n);
for(int i = 0; i < n; i++) {
scanf("%lld/%lld", &a, &b);
gcdvalue = (suma == 0 || sumb == 0) ? 1 : gcd(abs(suma), abs(sumb));
sumb = sumb / gcdvalue;
suma = suma / gcdvalue;
gcdvalue = (a == 0 || b == 0) ? 1 : gcd(abs(a), abs(b));
a = a / gcdvalue;
b = b / gcdvalue;
suma = a * sumb + suma * b;
sumb = b * sumb;
}
long long integer = suma / sumb;
suma = suma - (sumb * integer);
gcdvalue = (suma == 0 || sumb == 0) ? 1 : gcd(abs(suma), abs(sumb));
suma = suma / gcdvalue;
sumb = sumb / gcdvalue;
if(integer != 0) {
printf("%lld", integer);
if(suma != 0)
printf(" ");
}
if(suma != 0) {
printf("%lld/%lld", suma, sumb);
}
if(integer == 0 && suma == 0)
printf("0");
return 0;
}