NotAlpha102

Reduced fraction

Jul 7th, 2020
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.96 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. void reduce(int numerator, int denominator, int *reduced_numerator, int *reduced_denominator)
  4. {
  5.  
  6.     int remainder, m, n;
  7.  
  8.     /* Compute GCD */
  9.     m=numerator;
  10.     n=denominator;
  11.     while (n != 0)
  12.     {
  13.         remainder = m % n;
  14.         m = n;
  15.         n = remainder;
  16.     }
  17.  
  18.     /* Divide both numerator and denominator by GCD. The GCD
  19.     will be m */
  20.     *reduced_numerator = numerator/m;
  21.     *reduced_denominator = denominator/m;
  22.  
  23.     /* Ensure that denominator is positive */
  24.     if (*reduced_denominator < 0)
  25.     {
  26.         *reduced_numerator *= -1;
  27.         *reduced_denominator *= -1;
  28.     }
  29. }
  30.  
  31. int main()
  32. {
  33.     int num, denom, m, n, remainder, reduced_num, reduced_denom;
  34.  
  35.     printf("Enter a fraction: ");
  36.     scanf("%d/%d", &num, &denom);
  37.  
  38.  
  39.     m = num;
  40.     n = denom;
  41.     reduce(m, n, &reduced_num, &reduced_denom);
  42.  
  43.  
  44.  
  45.  
  46.  
  47.     printf("In lowest terms: %d/%d\n", reduced_num, reduced_denom);
  48.  
  49.     return 0;
  50. }
Advertisement
Add Comment
Please, Sign In to add comment