Java Reference
In-Depth Information
The output is 18446744073709551614 .
There is no limit to the precision of a BigDecimal object. The divide method may throw
an ArithmeticException if the result cannot be terminated. However, you can use the
overloaded divide(BigDecimal d, int scale, int roundingMode) method to spec-
ify a scale and a rounding mode to avoid this exception, where scale is the maximum number
of digits after the decimal point. For example, the following code creates two BigDecimal
objects and performs division with scale 20 and rounding mode BigDecimal.ROUND_UP .
BigDecimal a = new BigDecimal( 1.0 );
BigDecimal b = new BigDecimal( 3 );
BigDecimal c = a.divide(b, 20 , BigDecimal.ROUND_UP);
System.out.println(c);
The output is 0.33333333333333333334 .
Note that the factorial of an integer can be very large. Listing 10.9 gives a method that can
return the factorial of any integer.
L ISTING 10.9
LargeFactorial.java
1 import java.math.*;
2
3 public class LargeFactorial {
4 public static void main(String[] args) {
5 System.out.println( "50! is \n" + factorial( 50 ));
6 }
7
8
public static BigInteger factorial( long n) {
9
BigInteger result = BigInteger.ONE;
constant
10
for ( int i = 1 ; i <= n; i++)
11
result = result.multiply( new BigInteger(i + "" ));
multiply
12
13
return result;
14 }
15 }
50! is
30414093201713378043612608166064768844377641568960512000000000000
BigInteger.ONE (line 9) is a constant defined in the BigInteger class. BigInteger.ONE
is the same as new BigInteger("1") .
A new result is obtained by invoking the multiply method (line 11).
10.14
What is the output of the following code?
Check
Point
public class Test {
public static void main(String[] args) {
java.math.BigInteger x = new java.math.BigInteger( "3" );
java.math.BigInteger y = new java.math.BigInteger( "7" );
java.math.BigInteger z = x.add(y);
System.out.println( "x is " + x);
System.out.println( "y is " + y);
System.out.println( "z is " + z);
}
}
 
 
Search WWH ::




Custom Search