0
import java.math.BigInteger;
import java.util.ArrayList;

public class Factorial {

    public static int[] bitVector(int n) {
        ArrayList<Integer> bitList = new ArrayList<Integer>();
        BigInteger input = computeFactorial(n);
        System.out.println(input);
        BigInteger[] result = input.divideAndRemainder(new BigInteger(String.valueOf(2)));
        if (result[0].intValue()==0) {return new int[]{result[1].intValue()};}
        else {
            bitList.add(result[1].intValue());
        }
        while(result[0].intValue() != 0) {
            result = result[0].divideAndRemainder(new BigInteger(String.valueOf(2)));
            bitList.add(result[1].intValue());
        }
        int[] array = new int[bitList.size()];
        for (int i=0; i<array.length; i++) {
            array[i]=bitList.get(i).intValue();
        }
        return array;
    }

    public static BigInteger computeFactorial(int n) {
        if (n==0) {
            return new BigInteger(String.valueOf(1));
        } else {
            return new BigInteger(String.valueOf(n)).multiply(computeFactorial(n-1));
        }
    }

    public static void main(String[] args) {
        int[] bitVector = bitVector(35);
        for (int bit: bitVector)
        System.out.print(bit+" ");
        System.out.println();
    }
}

上記のコードは、への入力が。以下の場合に正常に機能しbitVectorます3536ただし、パラメータとしてに渡すとbitVector、1ビットを除くすべてが出力に含まれなくなります。

私は潜在的に次の原因を除外しました:

  1. BigIntegerタイプはオーバーフローしないように設計されているため、BigIntegerタイプとは関係がない可能性があります。

  2. 380M実行時にのみ使用するプログラムのメモリ使用量とは関係ない場合があります。

  3. の値を出力しますcomputeFactorial(36)。これはよさそうです。

いったい何が起こっているのでしょうか?

4

2 に答える 2

2

だからあなたがやろうとしていることは

public static String factorialAsBinary(int n) {
    BigInteger bi = BigInteger.ONE;
    for (; n > 1; n--)
        bi = bi.multiply(BigInteger.valueOf(n));
    return bi.toString(2);
}

public static void main(String... args) {
    String fact36 = factorialAsBinary(36);
    for (char ch : fact36.toCharArray())
        System.out.print(ch + " ");
    System.out.println();
}

印刷する

1 0 0 0 1 0 0 0 1 0 1 0 0 1 1 0 0 0 1 0 1 0 1 1 0 0 1 0 1 1 0 1 1 1 1 0 1 1 1 0 1 0 1 0 0 0 0 0 1 1 1 0 1 0 0 0 0 1 0 0 0 1 0 0 0 1 0 0 1 0 1 0 0 0 1 1 1 1 1 0 0 1 1 1 0 0 1 1 0 1 1 0 0 1 1 1 1 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

一体何が起こっているのですか?

あなたのコードは必要以上に複雑で、ミスを犯しやすく、理解しにくくなっています。

于 2013-02-04T09:18:56.913 に答える
1

result[0].intValue()間違っている:

intValue():

この BigInteger を int に変換します。この変換は、Java 言語仕様で定義されている long から int への縮小プリミティブ変換に似ています。この BigInteger が大きすぎて int に収まらない場合、下位 32 ビットのみが返されます。この変換により、BigInteger 値の全体的な大きさに関する情報が失われ、反対の符号の結果が返される可能性があることに注意してください。

あなたの場合、ゼロである最下位32ビットを返すため、最初の除算後に0を返します

于 2013-02-04T09:21:02.790 に答える