BigNum.java
Download BigNum.java
1: // Demo of using BigInteger and BigDecimal. Points to note:
2: // BigInteger doesn't provide an int or long constructor, so the
3: // static valueOf method is used.
4: // BigDecimal does have a double constructor, but it should never be used!
5: // There is also a BigDecimal constructor that uses a BigInteger.
6: //
7: // Written 8/2005 by Wayne Pollock, Tampa Florida USA.
8: // Updated 2022 by Wayne Pollock, for Java language changes.
9:
10: import java.math.*;
11: import static java.math.BigInteger.*;
12:
13: public class BigNum
14: {
15: public static void main ( String [] args )
16: {
17: int digit = 7; // a randomly chosen digit.
18:
19: BigInteger bi = valueOf( 12345679 ); // Note use of static import
20: BigInteger nine = new BigInteger( "9" ); // Note string constructor.
21:
22: bi = bi.multiply( nine );
23: bi = bi.multiply( BigInteger.valueOf( digit ) );
24:
25: System.out.println( "the result is: " + bi );
26:
27: BigDecimal num = BigDecimal.ZERO;
28: num = num.add( BigDecimal.valueOf( 3.14 ) );
29: num = num.divide( BigDecimal.valueOf( 2 ), RoundingMode.HALF_EVEN );
30:
31: System.out.println( "pi/2 = " + num );
32:
33: // Calculate odds of winning Florida lotto (pick 6 of 53 numbers):
34: // Formula for choosing 6 of 53 is: C(53, 6) = 53!/(6! * (53-6)!)
35:
36: System.out.println( "\nFlorida Lotto Odds of Winning\n" );
37:
38: final int possibleValues = 53;
39: final int numToPick = 6;
40:
41: BigInteger numerator = factorial( valueOf(possibleValues) );
42: BigInteger denominator = factorial(valueOf(numToPick)).multiply(
43: factorial(valueOf(possibleValues-numToPick)) );
44:
45: System.out.println( "numerator = " + numerator );
46: System.out.println( "demominator = " + denominator );
47:
48: BigInteger odds = numerator.divide( denominator );
49: System.out.println( "Odds of winning Florida lotto: 1 in " + odds );
50: }
51:
52: /** Computes num! = num * (num-1) * (num-2) * ... * 3 * 2 * 1
53: */
54: static BigInteger factorial ( BigInteger num )
55: {
56: if ( num.equals(ONE) ) // notice static import use!
57: return ONE;
58: return num.multiply( factorial( num.subtract(ONE) ) );
59: }
60: }