Joe
Joe

Reputation: 109

Java Fraction Addition Formula Trouble

I have a project for a class where you have to recieve two fractions from a user with different denominators, add them together and output them with the lowest common denominator. Since we have to use principles from only chapters we have covered I cannot make a fraction class so please don't suggest that. Basically I need to make a method(s) to add the fractions together. I am just trying to get the basic formula down for the methods so here is all the code I have for it right now. Any suggestions, tips, or help is greatly appreciated. :-)

//Joseph Biancardi
//IS1300 Spring 2015
public class FractionAddition{
public static void main(String[] args) {
    final int n1 = 2;
    final int n2 = 3;
    final int d1 = 3;
    final int d2 = 6;
    int c = 0;
    int e1 = 0;
    int e2 = 0;
    while(c == 0) {
        if(e1 == e2) {
            c = 2;
        }
        e1 =+ d1;
        if(e1 == e2) {
            c = 1;
        }
        e2 =+ d2;

    }
    System.out.println(e1 + " " + e2);
    int f1 = e1 / d1;
    int f2 = e2 / d2;
    int g1 = n1 * f1;
    int g2 = n2 * f2;
    int final1 = g1 + g2;
    System.out.println(n1 + " " + n2 + " equals" + " " + final1);
    System.out.println(d1 + " " + d2 + " equals" + " " + e1);
        }
    }

Upvotes: 3

Views: 268

Answers (1)

vojta
vojta

Reputation: 5651

Your way to find LCM is incorrect. You should compute e like this:

private static long gcd(long a, long b)
{
    while (b > 0)
    {
        long temp = b;
        b = a % b;
        a = temp;
    }
    return a;
}


private static long lcm(long a, long b)
{
    return a * (b / gcd(a, b));
}
...
e = lcm(d1, d2); //denominator
int f1 = e / d1;
int f2 = e / d2;
int g1 = n1 * f1;
int g2 = n2 * f2;
int final1 = g1 + g2;
int k = gcd(final1, e);
int final_nominator = final1 / k;
int final_denominator = e / k;

Note that my gcd algorithm is not an optimal one, its speed can be significantly improved.

Upvotes: 3

Related Questions