Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 1 #include <stdio.h>
- 2 #include <limits.h> // provides the constant INT_MAX
- 3 #include <stdlib.h> // provides abs function and malloc
- 4 #include "Fraction.h"
- 5 #include <assert.h>
- 6
- 7 int gcd(int a, int b)
- 8 {
- 9 if (a == 0 && b == 0) {
- 10 printf("Illegal args to gcd: %d, %d\n",a,b);
- 11 exit(1);
- 12 }
- 13 a = abs(a);
- 14 b = abs(b);
- 15 if (a == 0)
- 16 return b;
- 17 if (b == 0)
- 18 return a;
- 19 return gcd(b,a%b);
- 20 }
- 21
- 22 Fraction string_to_fraction(const char *S)
- 23 {
- 24 Fraction result = {0,1};
- 25
- 26 sscanf(S,"%d/%d",&result.numer, &result.denom);
- 27
- 28 reduce_fraction(&result);
- 29
- 30 return result;
- 31 }
- 32
- 33 char * fraction_to_string(Fraction R)
- 34 {
- 35 char *answer = (char*)(malloc(23));
- 36
- 37 if(R.denom == 1)
- 38 {
- 39 sprintf(answer, "%d", R.numer);
- 40 }
- 41
- 42 else
- 43 {
- 44 sprintf(answer, "%d/%d", R.numer, R.denom);
- 45 }
- 46
- 47 return answer;
- 48 }
- 49
- 50
- 51 int compare_fractions(Fraction L, Fraction R)
- 52 {
- 53
- 54 if((L.numer * R.denom) < (L.denom * R.numer))
- 55 return -1;
- 56
- 57 if((L.numer * R.denom) == (L.denom * R.numer))
- 58 return 0;
- 59
- 60 if((L.numer * R.denom) > (L.denom * R.numer))
- 61 return 1;
- 62 }
- 63
- 64 void reduce_fraction(Fraction *R)
- 65 {
- 66 int min, i;
- 67
- 68 if(R -> numer < R -> denom)
- 69 min = R -> numer;
- 70 else
- 71 min = R -> denom;
- 72
- 73 for(i = min; i >= 1; i--)
- 74 {
- 75 if(R -> numer % i == 0 && R -> denom % i == 0)
- 76 break;
- 77 }
- 78
- 79 R -> numer = R -> numer / i;
- 80 R -> denom = R -> denom / i;
- 81
- 82 }
- 83
- 84 Fraction add_fractions(Fraction L, Fraction R)
- 85 {
- 86 Fraction result = {0,1};
- 87
- 88 result.numer = L.numer * R.denom + R.numer * L.denom;
- 89 result.denom = L.denom * R.denom;
- 90
- 91 reduce_fraction(&result);
- 92
- 93 return result;
- 94 }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement