Problems adding Java Fraction formula

I have a project for a class where you need to get two fractions from a user with different denominators, add them together, and output them with the lowest common denominator. Since we only have to use principles from the chapters we've covered, I can't make a faction class, so please don't suggest that. Basically I need to do method (s) to add fractions together. I'm just trying to get a basic formula for the methods, so here's all the code I have for it right now. Any suggestions, advice or help is 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);
        }
    }

      

+3


source to share


1 answer


Invalid LCM lookup method. You should calculate e

as follows:

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;

      



Please note that my gcd algorithm is not optimal, its speed could be greatly improved.

+3


source







All Articles