Posted By

skiabox on 10/25/10

Statistics

Viewed 2288 times
Favorited by 0 user(s)

Reduce a fraction to lowest terms

/ Published in: C  To reduce a fraction to lowest terms, first we compute the GCD(greatest common divisor) of the numerator and denominator.
Then we divide both the numerator and denominator by the GCD.

Copy this code and paste it in your HTML
1. #include <stdbool.h>
2. #include <stdio.h>
3.
4. //gcf function - return gcd of two numbers
5. int gcd(int n, int m)
6. {
7. int gcd, remainder;
8.
9. while (n != 0)
10. {
11. remainder = m % n;
12. m = n;
13. n = remainder;
14. }
15.
16. gcd = m;
17.
18. return gcd;
19. }//end gcd function
20.
21. int main (int argc, const char * argv[]) {
22. // insert code here...
23. //--declarations
24. int number1, number2;
25. int newNumber1, newNumber2;
26.
27. //--get user input
28. printf("Enter a fraction: ");
29. scanf("%d/%d", &number1, &number2);
30.
31. //--calculations
32. //find the gcd of numerator and denominator
33. //then divide both the numerator and denominator by the GCD
34. newNumber1 = number1 / gcd(number1, number2);
35. newNumber2 = number2 / gcd(number1, number2);
36.
37. //--results
38. printf("In lowest terms: %d/%d", newNumber1, newNumber2);
39. } Subscribe to comments