-1

Leonhard Euler の予想を解決するために私が書いたこのプログラムを実装しようとすると、狂ったエラーが発生します。エラーはにあるようprintlnです。私が間違っていることを知っていますか?(プログラムを実行する前にエラーは発生せず、実行後にエラー メッセージが表示されます) 私が実装しているのはかなり単純なので、なぜ連携していないのかよくわかりません。

ps私は別のウェブサイトを読んでoutメッセージをStringオブジェクトとして割り当て、そのStringオブジェクトを出力しましたが、それは別のエラーメッセージをリストに追加するだけです。

    public static void main(String[] args) {

    BigInteger max = new BigInteger("Integer.MAX_VALUE");

    // for(int a=0; a<max; a++)
    for(BigInteger a=BigInteger.ZERO; a.compareTo(max)<=0; a=a.add(BigInteger.ONE)){

        for(BigInteger b=BigInteger.ZERO; b.compareTo(max)<=0; b=b.add(BigInteger.ONE)){

            for(BigInteger c=BigInteger.ZERO; c.compareTo(max)<=0; c=c.add(BigInteger.ONE)){

                for(BigInteger d=BigInteger.ZERO; d.compareTo(max)<=0; d=d.add(BigInteger.ONE)){

                    // a^4
                    a=a.pow(4);
                    // b^4
                    b=b.pow(4);
                    // c^4
                    c=c.pow(4);
                    // d^4
                    d=d.pow(4);

                    // a+b+c
                    BigInteger sum = new BigInteger("a.add(b).add(c)");

                    // if( sum == d^4 )
                    int euler = sum.compareTo(d);
                    if( euler ==0)
                    {
                        System.out.println(a+"^4+"+b+"^4+"+c+"^4="+d+"^4");
                    }  
                }
            }
        }
    }   
}
4

3 に答える 3

1

BigInteger@CommuSoftはあなたのエラーを特定しました(彼の答えを受け入れてください)が、 sに少し夢中になっていて、多くの冗長な計算を実行していることを指摘したかった. めちゃくちゃ多い。これははるかに効率的です:

public static void main(String[] args) {
    for (int a = -1; a++ < Integer.MAX_VALUE; ) {
        BigInteger a4 = BigInteger.valueOf(a).pow(4);

        for (int b = a - 1; b++ < Integer.MAX_VALUE; ) {
            BigInteger b4 = BigInteger.valueOf(b).pow(4);
            BigInteger partialSum = a4.add(b4);

            for(int c = b - 1; c++ < Integer.MAX_VALUE; ) {
                BigInteger c4 = BigInteger.valueOf(c).pow(4);
                BigInteger sum = partialSum.add(c4);

                for(int d = c - 1; d++ < Integer.MAX_VALUE; ) {
                    BigInteger d4 = BigInteger.valueOf(d).pow(4);

                    int euler = sum.compareTo(d4);
                    if( euler == 0)
                    {
                        System.out.println(a4+"^4+"+b4+"^4+"+c4+"^4="+d4+"^4");
                    } else if (euler < 0) {
                        // d4 is larger than the sum, and will only get bigger
                        break;
                    }
                }
            }
        }
    }   
}

これらの変更があっても、あなたが生きている間にこのコードが完全に実行されるとは思えません。実際、それはおそらく宇宙の存続期間内に完了することはありません。

于 2015-04-09T18:55:15.653 に答える