如何将 BigInteger 除以整数?
How to divide a BigInteger by integer?
(编辑:在更多人投反对票之前,我确实事先查看了 Javadoc,但由于我是初学者,我不确定在文档中的哪个位置查看。请参阅我对 Jim G 的回复,该回复发布在下面.我知道这个问题可能被认为太基础了。但我认为它对我这种情况的其他初学者有一定的价值。所以请在投票前从初学者的角度考虑完整的情况。)
我想将 BigInteger 除以一个常规整数(即 int),但我不知道该怎么做。我在 Google 和 Stack Exchange 上进行了快速搜索,但没有找到任何答案。
那么,如何将 BigInteger 除以 int?当我们这样做的时候,我如何才能 add/subtract BigInts 到 ints,比较 BigInts 到 ints,等等?
将 Integer
转换为 BigInteger
,然后将两者相除 BigInteger
,如下所示:
BigInteger b = BigInteger.valueOf(10);
int x = 6;
//convert the integer to BigInteger.
BigInteger converted = new BigInteger(Integer.toString(x));
//now you can divide, add, subtract etc.
BigInteger result = b.divide(converted); //but this will give you Integer values.
System.out.println(result);
result = b.add(converted);
System.out.println(result);
以上除法将为您提供 Integer
个除法值,要获得精确值,请使用 BigDecimal
.
编辑:
删除上面代码中的两个中间变量converted
和result
:
BigInteger b = BigInteger.valueOf(10);
int x = 6;
System.out.println(b.divide(new BigInteger(Integer.toString(x))));
或
Scanner in = new Scanner(System.in);
System.out.println(BigInteger.valueOf((in.nextInt())).divide(new BigInteger(Integer.toString(in.nextInt()))));
只需使用BigInteger.valueOf(long)
工厂方法。一个 int 可以隐式地 "widened" 为 long ...从小到大时总是这样,例如byte => short, short => int, int => long.
BigInteger bigInt = BigInteger.valueOf(12);
int regularInt = 6;
BigInteger result = bigInt.divide(BigInteger.valueOf(regularInt));
System.out.println(result); // => 2
(编辑:在更多人投反对票之前,我确实事先查看了 Javadoc,但由于我是初学者,我不确定在文档中的哪个位置查看。请参阅我对 Jim G 的回复,该回复发布在下面.我知道这个问题可能被认为太基础了。但我认为它对我这种情况的其他初学者有一定的价值。所以请在投票前从初学者的角度考虑完整的情况。)
我想将 BigInteger 除以一个常规整数(即 int),但我不知道该怎么做。我在 Google 和 Stack Exchange 上进行了快速搜索,但没有找到任何答案。
那么,如何将 BigInteger 除以 int?当我们这样做的时候,我如何才能 add/subtract BigInts 到 ints,比较 BigInts 到 ints,等等?
将 Integer
转换为 BigInteger
,然后将两者相除 BigInteger
,如下所示:
BigInteger b = BigInteger.valueOf(10);
int x = 6;
//convert the integer to BigInteger.
BigInteger converted = new BigInteger(Integer.toString(x));
//now you can divide, add, subtract etc.
BigInteger result = b.divide(converted); //but this will give you Integer values.
System.out.println(result);
result = b.add(converted);
System.out.println(result);
以上除法将为您提供 Integer
个除法值,要获得精确值,请使用 BigDecimal
.
编辑:
删除上面代码中的两个中间变量converted
和result
:
BigInteger b = BigInteger.valueOf(10);
int x = 6;
System.out.println(b.divide(new BigInteger(Integer.toString(x))));
或
Scanner in = new Scanner(System.in);
System.out.println(BigInteger.valueOf((in.nextInt())).divide(new BigInteger(Integer.toString(in.nextInt()))));
只需使用BigInteger.valueOf(long)
工厂方法。一个 int 可以隐式地 "widened" 为 long ...从小到大时总是这样,例如byte => short, short => int, int => long.
BigInteger bigInt = BigInteger.valueOf(12);
int regularInt = 6;
BigInteger result = bigInt.divide(BigInteger.valueOf(regularInt));
System.out.println(result); // => 2