Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //https://www.e-olymp.com/uk/problems/1017
- #include <stdio.h>
- #define lli long long int
- struct num {
- lli sign;
- lli integer;
- lli numerator;
- lli denominator;
- num() {
- sign = 1;
- integer = 0;
- numerator = 0;
- denominator = 1;
- }
- };
- lli cutNum(lli *pos, char s[]) {
- lli num = 0, fpos = *pos, d = 1;
- while (s[fpos] >= 48 && s[fpos] <= 57) {
- fpos++;
- }
- fpos--;
- for (lli i = fpos; i >= *pos; i--) {
- num += (s[i] - '0') * d;
- d *= 10;
- }
- *pos = fpos+1;
- return num;
- }
- void readNum(num *n) {
- char s[21];
- lli pos = 0, a = 0, b = 0, c = 0;
- gets(s);
- if (s[0] == '-') {
- pos++;
- (*n).sign = -1;
- }
- a = cutNum(&pos, s);
- if (s[pos] == '/') {
- (*n).numerator = a;
- pos++;
- b = cutNum(&pos, s);
- (*n).denominator = b;
- } else if (s[pos] == ' ') {
- (*n).integer = a;
- pos++;
- if (s[pos] != '\0') {
- b = cutNum(&pos, s);
- pos++;
- c = cutNum(&pos, s);
- (*n).numerator = b;
- (*n).denominator = c;
- }
- } else if (s[pos] == '\0') {
- (*n).integer = a;
- }
- }
- void printNum(num n) {
- if (n.integer == 0 && n.numerator == 0) printf("0");
- else {
- if (n.sign == -1) printf("-");
- if (n.integer != 0) printf("%lli ", n.integer);
- if (n.numerator != 0) printf("%lli/%lli", n.numerator, n.denominator);
- }
- printf("\n");
- }
- lli nod(lli a, lli b) {
- if (a == b) {
- return a;
- }
- while (a && b) {
- if (a > b) {
- a %= b;
- } else {
- b %= a;
- }
- }
- return a + b;
- }
- void simplify(lli *a, lli *b) {
- while (nod(*a, *b) != 1) {
- lli c = nod(*a, *b);
- *a /= c;
- *b /= c;
- }
- }
- num mult(num a, num b) {
- num c;
- lli m1 = a.integer*a.denominator + a.numerator;
- lli m2 = b.integer*b.denominator + b.numerator;
- lli n = m1*m2;
- lli d = a.denominator * b.denominator;
- simplify(&n, &d);
- c.integer = n/d;
- n -= d*c.integer;
- c.numerator = n;
- c.denominator = d;
- c.sign = a.sign*b.sign;
- return c;
- }
- num div(num a, num b) {
- lli c = b.numerator;
- b.numerator = b.denominator;
- b.denominator = c;
- return mult(a, b);
- }
- lli nok(lli a, lli b) {
- return a*b/nod(a, b);
- }
- num sum(num a, num b) {
- num c;
- lli n, d;
- d = nok(a.denominator, b.denominator);
- n = a.sign*a.integer*d + a.sign*a.numerator*d/a.denominator + b.sign*b.integer*d + b.sign*b.numerator*d/b.denominator;
- if (n < 0) {
- c.sign = -1;
- n *= -1;
- }
- simplify(&n, &d);
- c.integer = n/d;
- n -= d*c.integer;
- c.numerator = n;
- c.denominator = d;
- return c;
- }
- num dif(num a, num b) {
- b.sign *= -1;
- return sum(a, b);
- }
- num fn(char s, num a, num b) {
- if (s == '+') return sum(a, b);
- if (s == '-') return dif(a, b);
- if (s == '*') return mult(a, b);
- return div(a, b);
- }
- num a, b, c;
- char f;
- int main() {
- readNum(&a);
- scanf("%c\n", &f);
- readNum(&b);
- c = fn(f, a, b);
- printNum(c);
- return 0;
- }
Add Comment
Please, Sign In to add comment