Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Finding the greatest common divisor?

843785Nov 11 2008 — edited Nov 11 2008
I'm trying to right a program that solves the greatest common divisor. I always, get 0, or the program will never finish. Any help? I'm completely lost. =(
public class GCD extends MathOp
{
    /** A method public static int gcd (int one, int two) for
     *  MathOp: it returns the greatest common positive divisor of its two 
     *  int parameters. Hint: If either is negative, multiply it by -1; then
     *  repeatedly replace the larger by the remainder from dividing the larger 
     *  by the smaller until one goes evenly into the other, in which case
     *  that one will be the greatest common divisor. What do you do if either
     *  is zero? */

    public static int gcd (int one, int two)
    {   int gcd = 1;
        for (; gcd != 0; )
        {   if (two < 0)
                two = two * -1;
            if (one < 0)
                one = one * -1;
            if (two > one)
                gcd = (two % one);
            if (one > two)
                gcd = (one % two);
            if (one == two)
                gcd = (one % two);
        }
        return gcd;
    }
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Dec 9 2008
Added on Nov 11 2008
11 comments
350 views