簡體   English   中英

將很大的整數轉換為位向量失敗

[英]Converting very big integer to bit vector fails

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的輸入不大於35時,以上代碼可以正常工作。 但是,當我將36作為參數傳遞給bitVector ,輸出中除一位bitVector所有位都消失了。

我可能排除了以下原因:

  1. 它可能與BigInteger類型無關,因為它被設計為永不溢出。

  2. 它可能與程序的內存使用無關,該程序在運行時僅使用380M

  3. 我打印出了computeFactorial(36)的值,看起來不錯。

到底發生了什么事?

所以你想做的是

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 0 1 0 1 0 1 1 0 0 1 0 1 1 0 1 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 0 1 1 1 1 1 0 0 1 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 0 0 0 0 0

到底發生了什么事?

您的代碼比需要的要復雜得多,這也使錯誤更容易理解。

result[0].intValue()錯誤:

intValue():

將此BigInteger轉換為int。 此轉換類似於Java語言規范中定義的從long到int的窄原始轉換:如果此BigInteger太大而無法容納int,則僅返回低階32位。 請注意,此轉換可能會丟失有關BigInteger值的整體大小的信息,並且會返回帶有相反符號的結果。

在您的情況下,它返回的最低32位為零,因此您在第一次除法后將返回0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM