0

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 以下であることを確認するにはどうすればよいですか? そして、3 つの整数すべてを返しますか?

何をする必要があるかを理解するのに役立つ場合、コードの残りの部分は次のとおりです。

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

2 に答える 2

4

ユークリッドのアルゴリズムを使用して、aとのGCDを計算できますb。結果を呼び出しdます。次に、、、およびのGCDはabおよびcのGCDです。そのために、ユークリッドのアルゴリズムを再び使用できます。cd

于 2012-11-26T21:01:45.567 に答える
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になります。
于 2012-11-26T21:02:26.987 に答える