George
George

Reputation: 9

Adding, Subtracting, and Multiplying 2 fractions without creating a new variable Java

Directions: public void add(Fraction other) public void subtract(Fraction other) public void multiply(Fraction other) are void methods. They do not return anything. These methods should not create a new Fraction and return it.

Instead, these methods should modify the instance variables to be added, subtracted, or multiplied by the Fraction other. How should I go about doing this?

Upvotes: 0

Views: 1525

Answers (2)

null_awe
null_awe

Reputation: 483

For adding and subtracting, find the least common multiple of the denominators, and transform both fractions to have equal denominators. Then, add/subtract (depending on the operation) the numerators.

For multiplying, simply multiply both numerators together and denominators together.

For all operations, find the greatest common factor of the new numerator and denominator at the end, and divide both of them by that greatest common factor.

Code for gcf/lcm: https://javarevisited.blogspot.com/2016/07/how-to-calculate-gcf-and-lcm-of-two-numbers-in-java-example.html#axzz6eIo30y15

In order to be a void function, just edit the numerator/denominator of the first fraction instead of returning a new one.

The code would look something like this:

class Fraction {

  int numer;
  int denom;

  public Fraction(int n, int d) {
    numer = n;
    denom = d;
  }

  public void add(Fraction other) {
    numer *= other.denom;
    other.numer *= denom;
    denom *= other.denom;
    other.denom = denom;

    numer += other.numer;

    int gcd = gcd(numer, denom);
    numer /= gcd;
    denom /= gcd;
  }

  public void subtract(Fraction other) {
    numer *= other.denom;
    other.numer *= denom;
    denom *= other.denom;
    other.denom = denom;

    numer -= other.numer;

    int gcd = gcd(numer, denom);
    numer /= gcd;
    denom /= gcd;
  }

  public void multiply(Fraction other) {
    numer *= other.numer;
    denom *= other.denom;

    int gcd = gcd(numer, denom);
    numer /= gcd;
    denom /= gcd;
  }

  public int gcd(int a, int b) {
    // code from the website goes here
  }

Hope this is explained well enough!

Upvotes: 1

Will Metcher
Will Metcher

Reputation: 311

Assuming Fraction looks something like this:

public class Fraction {
 
    private int numerator = 1;
    private int denominator = 2;    

    public void multiply(Fraction other) {
        numerator *= other.getNumerator();
        denominator *= other.getDenominator();
    }

    public int getNumerator() {
        return numerator;
    }

    public int getNumerator() {
        return numerator;
    }
}

Hopefully this explains it.

Upvotes: 0

Related Questions