如何在单个方法中找到三个数字的GCD

时间:2012-11-26 20:56:22

标签: java int greatest-common-divisor

我必须确保3个数字之间的GCD不大于1。

这是我到目前为止的方法代码:

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

    return 1;
}
当我开始在实验室工作时,return 1已经存在了。如何确保GCD不超过1?并返回所有三个整数?

这是代码的其余部分,如果它有助于弄清楚需要做什么:

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";
}
}

更新

以下是我对同一个实验室的新编码:

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";
}
}

2 个答案:

答案 0 :(得分:4)

您可以使用Euclid's algorithm来计算ab的GCD。调用结果d。然后abc的GCD是cd的GCD;为此,您可以再次使用Euclid算法。

答案 1 :(得分:0)

如果你不关心效率,这是一种蛮力的方式:

private int greatestCommonFactor(int a, int b, int c)
{
    limit = Math.min(a, b);
    limit = Math.min(limit, c);
    for(int n = limit; n >= 2; n--)
    {
        if ( (a % n == 0) && (b % n == 0) && (c % n == 0) ) {
            return n;
        }
    }

    return 1;
}

<强>解释

  • 只需检查(a, b, c)的最小值,即可节省一些工作量。任何大于此数字的数字肯定不会是所有3的GCD。
  • 您需要在n = limit而不是n = 0开始循环并向后计数。
  • 一旦我们遇到一个为(a, b, c)产生零余数的数字,那就必须是GCD。
  • 如果循环内未找到任何内容,则GCD默认为1。