Search code examples
javaintgreatest-common-divisor

How to find the GCD of three numbers within a single method


I've got to ensure that the GCD between 3 numbers is no greater than 1.

Here's the code I have so far for the method:

private int greatestCommonFactor(int a, int b, int c)
{
    for(int n = 0; n <= number; n++)
    {
        if()
    }

    return 1;
}

the return 1 was already there when I started working on the lab. How can I make sure that the GCD is no more than 1? And return all three integers?

Here's the remainder of the code if it helps in figuring out what needs to be done:

import static java.lang.System.*;

public class Triples
{
 private int number;

public Triples()
{
    this(0);
}

public Triples(int num)
{
    number = num;
}

public void setNum(int num)
{
    number = num;
}

private int greatestCommonFactor(int a, int b, int c)
{
    for(int n = 0; n <= number; n++)
    {
        if()
    }

    return 1;
}

public String toString()
{
    String output="";
    int max = number;
    for(a = 1; a <= max; a++)
    {
        for(b = a +1; b <= max; b++)
        {
            for(c = b + 1; c <= max; c++)
            {
                if(Math.pow(a, 2)+ Math.pow(b, 2)== Math.pow(c, 2))
                {
                    if((a%2==1 && b%2==0)|| (a%2==0 && b%2==1))
                }
            }
        }
    }


    return output+"\n";
}
}

UPDATE

Here is my new coding for the same lab:

import static java.lang.System.*;

public class Triples
{
 private int number;

public Triples()
{
    this(0);
}

public Triples(int num)
{
    number = num;
}

public void setNum(int num)
{
    number = num;
}

private int greatestCommonFactor(int a, int b, int c)
{
    for(int n = 0; n <= number; n++)
    {
    int max = number;
    for(a = 1; a <= max; a++)
    {
        a = n;
        for(b = a +1; b <= max; b++)
        {
            b =n;
            for(c = b + 1; c <= max; c++)
            {
                c = n;
                if(Math.pow(a, 2)+ Math.pow(b, 2)== Math.pow(c, 2))
                {
                    if((a%2==1 && b%2==0)|| (a%2==0 && b%2==1))
                    {
                        if(a%2<=1 && b%2<=1 && c%2<=1)
                        {
                            return 1;
                        }
                    }
                }
            }
        }
    }
    }

    return 1;
}

public String toString()
{
    String output="";
    output = greatestCommonFactor(a, b, c);


    return output+"\n";
}
}

Solution

  • You can use Euclid's algorithm to calculate the GCD of a and b. Call the result d. Then the GCD of a, b, and c is the GCD of c and d; for that, you can use Euclid's algorithm again.