armath.c 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #include <stdio.h>
  2. int gcd(int, int);
  3. long gcdl(long, long);
  4. void simplifyfraction(int*, int*);
  5. void simplifyfractionl(long*, long*);
  6. /* god bless euclid */
  7. int gcd(int a, int b) {
  8. int t;
  9. while (b) {
  10. t = a;
  11. a = b;
  12. b = t % b;
  13. //printf("t %i a %i b %i\n", t, a, b);
  14. }
  15. return a;
  16. }
  17. /* long variant */
  18. long gcdl(long a, long b) {
  19. long t;
  20. while (b) {
  21. t = a;
  22. a = b;
  23. b = t % b;
  24. //printf("t %i a %i b %i\n", t, a, b);
  25. }
  26. return a;
  27. }
  28. /* set the pointed address of an existing fraction to its simplified version */
  29. void simplifyfraction(int *num, int *denom) {
  30. int n = *num;
  31. int d = *denom;
  32. /* check for div by 0 */
  33. if (d == 0) {
  34. fprintf(stderr, "division by 0, result undefined\n");
  35. exit(1);
  36. }
  37. /* get gcd */
  38. int comdiv = gcd(n, d);
  39. /* reduce */
  40. n = n / comdiv;
  41. d = d / comdiv;
  42. *num = n;
  43. *denom = d;
  44. }
  45. /* long variant */
  46. void simplifyfractionl(long *num, long *denom) {
  47. long n = *num;
  48. long d = *denom;
  49. /* check for div by 0 */
  50. if (d == 0) {
  51. fprintf(stderr, "division by 0, result undefined\n");
  52. exit(1);
  53. }
  54. /* get gcd */
  55. long comdiv = gcd(n, d);
  56. /* reduce */
  57. n = n / comdiv;
  58. d = d / comdiv;
  59. *num = n;
  60. *denom = d;
  61. }