繁体   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