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:
9: import java.math.*;
10: import static java.math.BigInteger.*;
11:
12: public class BigNum
13: {
14:    public static void main ( String [] args )
15:    {
16:       int digit = 7;  // a randomly chosen digit.
17:
18:       BigInteger bi = BigInteger.valueOf( 12345679 );
19:       BigInteger nine = new BigInteger( "9" );  // Note string constructor.
20:
21:       bi = bi.multiply( nine );
22:       bi = bi.multiply( BigInteger.valueOf( digit ) );
23:
24:       System.out.println( "the result is: " + bi );
25:
26:       BigDecimal num = BigDecimal.ZERO;
27:       num = num.add( BigDecimal.valueOf( 3.14 ) );
28:       num = num.divide( BigDecimal.valueOf( 2 ), BigDecimal.ROUND_HALF_EVEN );
29:
30:       System.out.println( "pi/2 = " + num );
31:
32:       // Calculate odds of winning Florida lotto (pick 6 of 53 numbers):
33:       // Formula for choosing 6 of 53 is: C(53, 6) =  53!/(6! * (53-6)!)
34:
35:       System.out.println( "\nFlorida Lotto Odds of Winning\n" );
36:
37:       final int possibleValues = 53;
38:       final int numToPick = 6;
39:
40:       BigInteger numerator = factorial( valueOf(possibleValues) );
41:       BigInteger denominator = factorial(valueOf(numToPick)).multiply(
42:          factorial(valueOf(possibleValues-numToPick)) );
43:
44: System.out.println( "numerator = " + numerator );
45: System.out.println( "demominator = " + denominator );
46:
47:       BigInteger odds = numerator.divide( denominator );
48:       System.out.println( "Odds of winning Florida lotto: 1 in " + odds );
49:    }
50:
51:    // Computes num * (num-1) * (num-2) * ... * 3 * 2 * 1
52:    static BigInteger factorial ( BigInteger num )
53:    {
54:       if ( num.equals(ONE) )  // notice static import use!
55:          return ONE;
56:       return num.multiply( factorial( num.subtract(ONE) ) );
57:    }
58: }
```