Skip to main content
Logo image

Problem Solving with Algorithms and Data Structures using Java: The Interactive Edition

Section 1.18 Introduction: Exercises

Exercises Exercises


Implement the simple methods getNumerator and getDenominator that will return the numerator and denominator of a fraction.


In many ways it would be better if all fractions were maintained in lowest terms right from the start. Modify the constructor for the Fraction class so that gcd is used to reduce fractions immediately. Notice that this means the add function no longer needs to reduce. Make the necessary modifications.


Implement the remaining simple arithmetic operators as methods: sub, mul, and div.


Implement the compareTo method.


In the definition of fractions we assumed that negative fractions have a negative numerator and a positive denominator. Using a negative denominator might cause some of the comparisons to give incorrect results. In general, this is an unnecessary constraint. Modify the constructor to allow the user to pass a negative denominator so that all of the operators continue to work properly.
You have attempted of activities on this page.