Advertisement
Guest User

Untitled

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